reactjswebpackcss-loaderwebpack-style-loader

How to apply module wise class mapping for all css files inside a specific folder only


How to apply module wise class mapping for all CSS files inside a specific folder only

I have added the code below but it doesn't work

  {
    test: /.css$/i,
    use: [
      "style-loader", 
      //"css-loader"
      {
          loader: "css-loader",
          options: {
            importLoaders : 1,
            modules: {
              //localIdentName: "[name][local][hash:base64:5]",
              //localIdentContext: path.resolve(dirname, "src/styles"),
              mode: "local",
              auto: true,
              exportGlobals: true,
              localIdentName: "[name][local]__[hash:base64:5]",
              localIdentContext: path.resolve(__dirname, "src/styles"),
              localIdentHashSalt: "my-custom-hash",
              namedExport: true,
              exportLocalsConvention: "camelCase",
              exportOnlyLocals: false,
            },
            sourceMap: true,
          },
      }
    ],
    
  },

My Reactjs folder structure sample is given below

src
 styles // Webpack dynamic class should apply for all classes inside this only
  contact.css
  about.css
global.css // Dont apply webpack dynamic class

Solution

  • I have Achieved using the following code

    {
        test: /\.(css|scss)$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: {
                localIdentName: "[name]__[local]___[hash:base64:5]",
              },
              sourceMap: false
            }
          }
        ],
        include: /\.module\.css$/
      },
      {
        test: /\.(css|scss)$/,
        use: [
          'style-loader',
          //'css-loader'
          {
            loader: 'css-loader',
            options: {
              sourceMap: false
            }
          }
        ],
        exclude: /\.module\.css$/
      },
    

    Note: The css file to apply module should have the filename as [yourname].module.css and just include that in a component For example AboutComponent and COntactComponent add css as follows about.module.css & contact.module.css