3

When using webpack and babel together, one needs to configure both in order to use React CSS Modules. For example:

webpack.config.js will need a rule like this:

{
  // Translates CSS into CommonJS modules
  loader: 'css-loader',
  options: {
    modules: {
      mode: "local",
      localIdentName: CSS_CLASS_NAME_PATTERN,
    },
  sourceMap: true
}

babel.config.js will need a plugin like this:

[
  'react-css-modules',
  {
    generateScopedName: CSS_CLASS_NAME_PATTERN,
    filetypes: {
      '.scss': {
        syntax: 'postcss-scss',
        plugins: ['postcss-nested']
      }
    },
  }
]

Why the need to configure CSS Modules in two places? How the two work together? I.e. what happens in what order?

1 Answer 1

7

They don't. css-loader does its own thing: class name transformation in CSS, and replacement of CSS imports in JS code by mappings between original and generated names.

babel-plugin-react-css-modules works independently, and it replaces styleName attributes of react components by className with correct generated names. To do so it calculates class name mappings independently from css-loader, that's why it needs separate configuration matching that of css-loader, and that's why after a few years being abandoned by its creators it has compatibility issues with latest css-loader (css-loader changed internal class name generation logic).

Shameless self-promo: I maintain an up-to-date fork of babel-plugin-react-css-modules which solves compatibility issues with latest css-loader versions.

Sign up to request clarification or add additional context in comments.

3 Comments

Why not send a PR into the poorly maintained original repo? The current maintainer reviews PRs from my recent experience.
Nah... the original plugin lost its compatibility with css-loader in August 2020, with release of [email protected], and it took the "maintainer" four months even to comment on the thread where it was reported: github.com/gajus/babel-plugin-react-css-modules/issues/291 It took me just a few days to fork, fix, and release my own version ¯\_(ツ)_/¯
There's been no more releases of the old version since May 2019 so I'll be trying this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.