Search code examples
javascriptwebpackcss-modulesreact-css-modules

How to set up css-modules?


Official documentation way too complicated and not working for me. Does anyone know any good article how to set up css-modules with webpack?

react-css-modules didn't help either

Update

Here is my modules config. It was edited while trying to reach my goal, so it differs from original.

module: {
    rules: [
        { test: /\.js$/, exclude: /node_modules/, loader: "react-hot-loader!babel-loader" },
        {
            test: /\.scss$/,
            use: [{
                loader: "style-loader"
            }, {
                loader: "css-loader"
            }, {
                loader: "sass-loader"
            }]
        }, {
            test: /\.png$/,
            loader: 'file-loader?name=[name]--[hash].[ext]',
        }
    ],
    loaders: [{
        test: /\.css/,
        loader: 'style-loader!css-loader&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
    }, {
      test: /\.html$/,
      loader: 'file-loader',
    }]
},

Solution

  • It's fairly simple

    You need style-loader, css-loader and set module mode.

    {
      test: /\.css$/,
      loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' 
    }
    

    Like that. Where [name]__[local]___[hash:base64:5] indicates structure of your css classes that webpack will generate for you.

    I recommend follow this guide, is really that simple. https://github.com/css-modules/webpack-demo