TSDX incorporates Rollup under the hood to bundle CSS Modules, even though they are not referenced

I have recently developed a React library with TSDX and you can find it here: https://github.com/deadcoder0904/react-typical

This library utilizes CSS Modules and applies styles to the React components.

Although the bundle successfully generates a CSS file in the dist/ directory, it does not reference it properly which results in the styles not being applied.

As a result, the styles are not displayed as intended.

Below is the content of my tsdx.config.js file:

const postcss = require('rollup-plugin-postcss');
const { terser } = require('rollup-plugin-terser');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');

module.exports = {
  rollup(config, options) {
    config.plugins.push(
      postcss({
        modules: true,
        plugins: [
          autoprefixer(),
          cssnano({
            preset: 'default',
          }),
        ],
        inject: false,
        extract: !!options.writeMeta,
        minimize: true,
      }),
      terser()
    );
    return config;
  },
};

Upon exploring the dist/ directory at https://yarnpkg.com/package/@deadcoder0904/react-typical?files, you may observe that while there is an index.js file, it does not reference the accompanying .css file.

The same issue persists with all the .js files in the dist/ folder, where none of them reference the .css file, leading to the CSS code not being bundled and applied to the components.

How can I address this problem effectively?

Answer №1

It is common for libraries to introduce components and styles separately, with users being informed in the documentation that they need to import the CSS file if they want to use the default styles. For example:

import ReactTypical from "react-typical"
import "react-typical/dist/react-typical.cjs.development.css"

It seems like your situation is similar to this scenario.

Alternatively, you could set the styles by default without requiring manual imports. This can be achieved by configuring your settings to set inject: true, which will import the CSS context into your JavaScript file and execute it at runtime to add the styles to the <head /> of the document. Your updated configuration might look like this:

postcss({
  modules: true,
  plugins: [
    autoprefixer(),
    cssnano({
      preset: 'default',
    }),
  ],
  // Append to <head /> as code running
  inject: true,
  // Keep it as false since we don't extract to css file anymore
  extract: false,
})

Answer №2

To successfully integrate storybook into your project, be sure to include the necessary CSS rules in your webpack storybook configuration file at ./story/main.js:

// Remove any existing CSS rule
config.module.rules = config.module.rules.filter(
  f => f.test.toString() !== '/\\.css$/'
);
  
config.module.rules.push(
  {
    test: /\.css$/,
    use: [
      'style-loader',
      'css-loader',
    ],
    include: path.resolve(__dirname, "../src"),
  }
)

If you haven't already installed them in your package dependencies, remember to add the following packages:

npm i -D style-loader css-loader

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform Typescript code into Javascript using webpack while preserving the folder organization

Is there a way for webpack to compile my typescript node project into js while preserving the directory structure and not bundling into one file? This is my current project structure: src |_controllers |_home |_index.ts |_ services ...

Challenges of Using Flexbox in Media Queries

How can I use flex boxes in CSS to ensure that from a min-width of 769px to 1025px, the third figure is displayed on a new line while the first and second figures remain on the top line taking up equal space? <div class="mid-col-section-2"> <figu ...

Activate a webpage upon enabling/disabling a Chrome extension

In my current setup within the useEffect of my React component, I have a setInterval function set to run every second. This function calls chrome.runtime.sendMessage() to listen for messages from a Chrome extension. In the background script of the Chrome e ...

Using setTimeout in Node.js

I've been struggling to find a solution for slowing down the timeout in my code. The issue is that it runs too quickly, and I can't seem to figure out how to adjust it using Request. Everything else in the code works perfectly. var Scraper = fun ...

When using AngularJS in conjunction with Karma-Jasmine, it is important to note that the functions verifyNoOutstandingExpectation() and verifyNoOutstandingRequest() may not

There is an unresolved HTTP request that needs to be flushed. When I use the following code afterEach(function(){ $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); The code functions correctly and I ...

Convert individual packages within the node_modules directory to ES5 syntax

I am currently working on an Angular 12 project that needs to be compatible with Internet Explorer. Some of the dependencies in my node_modules folder are non es5. As far as I know, tsc does not affect node_modules and starts evaluating from the main opti ...

The outcome is not displayed in the appropriate section of the text

There seems to be an issue as the console is not displaying the response to the input, such as "the answer is correct" or "the answer is either empty or incorrect". <!DOCTYPE html> <html lang="en"> <head> <title>Hello!</ ...

What is the best way to have a div created by JavaScript automatically expand to cover the entire screen after clicking on a dynamically generated table cell?

A unique interactive game inspired by Jeopardy is in the works. By clicking on a specific element within the game board, players can reveal questions fetched from the Jeopardy API. These questions are then presented elegantly within a dynamically created d ...

Guidelines for setting the Id and value for a Hidden field

I am working with a gridview that has a few rows and columns, each containing ListBox Controls. Markup: <asp:GridView ID="gvDataEntry" runat="server" AutoGenerateColumns="False" <Columns> <ItemTemplate> <asp:ListBox ID="lst ...

TypeScript Add Extract Kind

I am currently working on implementing a function called sumPluck. This function will allow the user to specify a property of type number from an object in an array, and then calculate the sum of all those properties. For example: type A = { prop: number ...

Enhance the appearance of your Dojo TabContainer when viewing in Internet Explorer

Firefox seems to handle the following code without any issues: < div style="position:absolute;top:0px;margin-top:60px;bottom:0px;width:100%"> < div id="mainTabContainer" dojoType="dijit.layout.TabContainer" style="width:100%;height:100%"> {% fo ...

Error encountered when using the module export in Node.js

I have a file named db.js which contains the following code: var mysql = require('mysql2'); var mysqlModel = require('mysql-model'); var appModel = mysqlModel.createConnection({ host : 'localhost', us ...

Tips for extracting the values of multiple input fields in JavaScript and displaying them on a webpage

I want to collect all the values from input fields and display them on the website. Check out my code snippet below: var button = document.querySelector("button"); button.addEventListener("click", function() { var inputs = document.querySelectorAll( ...

I did not anticipate the React setState function to behave in the manner it did

While working on form validation for my page, I came across a tutorial showcasing a validation method that seems to be functioning correctly. However, there is one aspect that I am struggling to grasp. The tutorial suggests declaring a variable before the ...

Having trouble getting a background image to show up using node.js?

Hi there, I have a quick and simple question. I am attempting to include a div with a background-image in my *.ejs page file. <style> .signPage{ background-image: url("//back.jpg"); width: 98%; height: 98vh; top: ...

CSS3 stackable-design

How can I avoid CSS3 elements from overlapping? They are all <span> precious </span> <span> and </span> <span> cute </span> And here is my current CSS code span { margin : 20px; min-width: 150px; border-r ...

The React Native scrollToIndex function is ineffective on Android devices

I am facing an issue where the scrollToIndex function is working on iOS but not on Android. Any suggestions on how to fix this? this.list.scrollToIndex({animated: true, index: tempIndex, viewOffset:0,viewPosition:0}); Here is my flatlist code: <FlatL ...

CSS: incorrect text alignment

I'm encountering an error with text-align. I want my text aligned to the left, but it's starting from the center. I've tried to fix it without success. Can someone please review and correct my code? CSS .text { width: 100%; height: ...

An easy way to insert a horizontal line between your text

Currently, I have two text responses from my backend and I'm considering how to format them as shown in the design below. Is it possible to automatically add a horizontal line to separate the texts if there are two or more broadcasts instead of displa ...

What is the best way to store and retrieve all the variable data from a .js file on a user's device?

I'm looking for a way to save and load multiple variables in JavaScript that determine a "save" state. These variables are stored in a file named "variables.js." Is there a simple method to easily save all the information in this file and then load i ...