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

北慕城南 提交于 2020-07-09 11:57:07

问题


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 happened

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;
}


回答1:


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



来源:https://stackoverflow.com/questions/62237725/webpack-loader-configuration-to-load-css-and-sass-files-for-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!