How to avoid having injected CSS styles discarded by tree shaking?

505 Views Asked by At

I am using Rollup to bundle a React component. This component is later used in a React application bundled with Webpack. The component uses styles defined in two CSS modules -- one containing global styles and one with specific styles for the component itself.

To bundle the CSS modules I use rollup-plugin-postcss with default options. This means the CSS modules are converted into JS files, which are later injected into the document using style-inject.

To provide a more clear picture this is how my project looks like:

|- examples/example  // this is the example App
|- packages/test-css // this is the component
|  |- src
|  |  |- index.module.css       // global styles
|  |  |- index.ts               // this file imports index.module.css
|  |  |- myComponent.module.css // component-related styles
|  |  |- myComponent.tsx        // this file imports myComponent.module.css

The Rollup bundle does contain the code related to style injection both for the global and component-related styles. But,the Webpack bundle for the application only contains the component-related styles (the contents of myComponent.module.css are present, but not the ones from index.module.css).

I have tried excluding *.css.mjs files (the ones generated by Rollup) from being tree-shaken, but I still have the same issue. Since the React application directly imports MyComponent it seems Webpack bypasses index.ts (where the global styles are imported) altogether.

Is there a way to instruct Webpack not to discard the CSS modules imported in index.ts without completely disabling tree shaking? (if tree shaking is disabled all the styles are loaded).

I am including a repository to reproduce the example: https://github.com/xorxsan/test-css.

0

There are 0 best solutions below