Search code examples
javascriptreactjswebpackcss-loadersass-loader

Webpack loader configuration to load css and sass files for React JS


I have installed react-h5-audio-player in a React app made with create-react-app and it worked fine.

I did same to customized React project and I am being asked to configure webpack to load the css files.

webpack.config.js

module.exports = {
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader"
          }
        }
      ]
    }
  };

I have attached screenshot of error log and code section where error happenedenter image description here

The error (

ERROR in ./node_modules/react-h5-audio-player/lib/styles.css 1:0
Module parse failed: Unexpected token (1:0)

) happened in the below css file, these css files are made by installed audio player (which is made with typescript)

.rhap_container {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  line-height: 1;
  font-family: inherit;
  width: 100%;
  padding: 10px 15px;
  background-color: #fff;
  box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.2);
}
.rhap_container:focus:not(:focus-visible) {
  outline: 0;
}


Solution

  • You need to add css-loader and style-loader to enable your webpack to bundle CSS files:

    Install the loaders:

    npm install css-loader style-loader --save-dev
    npm install sass-loader node-sass --save-dev
    

    Set the rules in webpack config:

    module.exports = {
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: "babel-loader"
            }
          },
          {
            test: /\.css$/,
            loader: ["style-loader", "css-loader"],
          },
          {
            test: /\.s[ac]ss$/i,
            use: [
              // Creates `style` nodes from JS strings
              'style-loader',
              // Translates CSS into CommonJS
              'css-loader',
              // Compiles Sass to CSS
              'sass-loader',
            ],
          },
        ]
      }
    };
    

    Check css-loader, style-loader and sass-loader