Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup babel-plugin-react-css-modules in create-react-app?

I really like the separation of className and styleName that babel-plugin-react-css-modules offers for global and local styles respectively, but have had some trouble getting the plugin to work with create-react-app.

I've tried installing the plugin by running

npm install babel-plugin-react-css-modules --save

... as it says to do in the project (github https://github.com/gajus/babel-plugin-react-css-modules#css-modules) ...

... and have also used craco as suggested in a similar thread (#5113) to help overcome the limitations of create-react-app without the need to eject, but am still unable to import a scss file and reference to it using styleName.

Does anyone know if I'm missing something else here? Sorry if it's a noob question, I'm new to React and have been looking for a solution to this for a while now.

like image 707
Weardian Avatar asked Oct 31 '25 10:10

Weardian


1 Answers

1. add the plugin to .babelrc first.

  "plugins": [
      ["babel-plugin-react-css-modules",
      {
        "webpackHotModuleReloading": true,
        "autoResolveMultipleImports": true
      }],.... 
  ]

2. add css rule in webpack.config.js.

below is my configuration that you can reference from.

make sure that

2.1 option modules set to true.

2.2 localIdentName follow this format. localIdentName: "[path]___[name]__[local]___[hash:base64:5]"

 module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: "babel-loader",
            options: { cacheDirectory: true }
          }
        ]
      },
      {
        test: /\.css$/i,
        use: [
          {
            loader: ExtractCssChunks.loader,
            options: { hot: true }
          },
          {
            loader: "css-loader", //generating unique classname
            options: {
              importLoaders: 1, // if specifying more loaders
              modules: true,
              sourceMap: false,
              localIdentName: "[path]___[name]__[local]___[hash:base64:5]" //babel-plugin-css-module format
              //localIdentName: "[path][name]__[local]" //recommended settings by cssloader#local-scope , this option generate unique classname for compiled css
            }
          }
        ]
      },
like image 90
LancerAce Avatar answered Nov 02 '25 01:11

LancerAce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!