2

I got hit with a very peculiar problem when trying to import a CSS file from a node module.

In my App.tsx file, I have

import './App.css';                       // works
import '@foo/my-dependency/dist/foo.css'; // doesn't work

While importing local CSS file works nicely, importing foo.css from a node module does not work at all, yet no compilation error is observed.

And if I change that line to require syntax, it works normally.

require('@foo/my-dependency/dist/foo.css'); // works

And if I change it to CSS module like syntax, it works as well.

import style from '@foo/my-dependency/dist/foo.css'; // works
console.log(style);     // to ensure the imported stuff is used at least once

Note to support above I need to add CSS module type declaration as mentioned here.

I am not sure where exactly it is going wrong. My Webpack config on module rules looks like below. And I use webpack dev server for testing. Webpack version is 5.23.0.

  module: {
    rules: [
      {
        test: /\.(jsx?|tsx?)$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.s?css$/,
        use: [
          'style-loader',
          'css-loader',
          'postcss-loader',
          'sass-loader',
        ],
      }
    ],
  },
Ruifeng Ma
  • 2,399
  • 1
  • 22
  • 40

1 Answers1

1

Sometimes I get really surprised how good I am at tripping myself over. This is caused by a sideEffects: false setting I put into the package.json file of my dependency package to support Webpack tree shaking. It is specifically mentioned in the doc that css/scss files need to be marked as side effects in case they get pruned as an unwanted result. After changing to sideEffects: ["*.css"] everything works.

It's no surprise either that the other two working solutions I listed above are valid because when Webpack does tree shaking, it traverses through the import statements starting from the entry file. If it's not an import statement or the imported stuff is specifically used, surely tree shaking won't take effect.

Ruifeng Ma
  • 2,399
  • 1
  • 22
  • 40