为 React JS 加载 css 和 sass 文件的 Webpack 加载器配置
Webpack loader configuration to load css and sass files for React JS
我已经在使用 create-react-app 制作的 React 应用程序中安装了 react-h5-audio-player,并且运行良好。
我对定制的 React 项目做了同样的事情,我被要求配置 webpack 以加载 css 文件。
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
};
我已附上错误日志的屏幕截图和发生错误的代码部分
错误(
ERROR in ./node_modules/react-h5-audio-player/lib/styles.css 1:0
Module parse failed: Unexpected token (1:0)
) 发生在下面的 css 文件中,这些 css 文件是由安装的音频播放器制作的(使用打字稿制作)
.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;
}
您需要添加 css-loader
和 style-loader
以使您的 webpack 能够捆绑 CSS
个文件:
安装加载程序:
npm install css-loader style-loader --save-dev
npm install sass-loader node-sass --save-dev
在webpack配置中设置规则:
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',
],
},
]
}
};
勾选css-loader, style-loader and sass-loader
我已经在使用 create-react-app 制作的 React 应用程序中安装了 react-h5-audio-player,并且运行良好。
我对定制的 React 项目做了同样的事情,我被要求配置 webpack 以加载 css 文件。
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
};
我已附上错误日志的屏幕截图和发生错误的代码部分
错误(
ERROR in ./node_modules/react-h5-audio-player/lib/styles.css 1:0
Module parse failed: Unexpected token (1:0)
) 发生在下面的 css 文件中,这些 css 文件是由安装的音频播放器制作的(使用打字稿制作)
.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;
}
您需要添加 css-loader
和 style-loader
以使您的 webpack 能够捆绑 CSS
个文件:
安装加载程序:
npm install css-loader style-loader --save-dev
npm install sass-loader node-sass --save-dev
在webpack配置中设置规则:
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',
],
},
]
}
};
勾选css-loader, style-loader and sass-loader