简体   繁体   中英

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.

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
            }
          }
        ]
      },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM