在webpack安装style-loader的时候报Module build failed: CssSyntaxError
1,在执行打包的时候,具体错误信息如下:
G:\vue\代码\vue\webpack的使用\03-webpack的loader>npm run build
> webpackconfig@1.0.0 build G:\vue\代码\vue\webpack的使用\03-webpack的loader
> webpack
Hash: 446e3d1b59f2b335f4c1
Version: webpack 3.6.0
Time: 354ms
Asset Size Chunks Chunk Names
bundle.js 4.58 kB 0 [emitted] main
[0] ./src/main.js 338 bytes {0} [built]
[1] ./src/js/mathUtils.js 140 bytes {0} [built]
[2] ./src/js/info.js 95 bytes {0} [built]
[3] ./src/css/normal.css 711 bytes {0} [built] [failed] [1 error]
ERROR in ./src/css/normal.css
Module build failed: CssSyntaxError
(2:1) Unknown word
1 |
> 2 | var content = require("!!./normal.css");
| ^
3 |
4 | if(typeof content === 'string') content = [[module.id, content, '']];
@ ./src/main.js 15:0-27
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! webpackconfig@1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the webpackconfig@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2020-10-29T07_21_07_039Z-debug.log
错误原因在webpack.config.js:
- 使用多个loader时,是从右向左读取的。先加载css-loader,在加载style-loader,顺序不能乱。
- css-loader只负责将css文件进行加载,style-loader 负责将样式添加到DOM中。所以先解析css-loader,在把解析好的css文件添加DOM元素中。
错误webpack.config.js代码如下:
module:{
rules: [
{
test: /\.css$/,
use: [ 'css-loader' , 'style-loader' ]
}
]
}
正确webpack.config.js代码如下:
module:{
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
2,在次打包,会发现运行正常了:
> webpackconfig@1.0.0 build G:\vue\代码\vue\webpack的使用\03-webpack的loader
> webpack
Hash: 95866eb3ea3aa42dd259
Version: webpack 3.6.0
Time: 415ms
Asset Size Chunks Chunk Names
bundle.js 21.1 kB 0 [emitted] main
[0] ./src/main.js 338 bytes {0} [built]
[1] ./src/js/mathUtils.js 140 bytes {0} [built]
[2] ./src/js/info.js 95 bytes {0} [built]
[3] ./src/css/normal.css 1.1 kB {0} [built]
[4] ./node_modules/css-loader/dist/cjs.js!./src/css/normal.css 184 bytes {0} [built]
+ 3 hidden modules
G:\vue\代码\vue\webpack的使用\03-webpack的loader>