Webpack无法构建项目,因为无法解析图像。
项目结构project/
├─ node_modules/
├─ src/
│ ├─ assets/
│ │ ├─ images/
│ │ ├─ styles/
├─ package.json
├─ webpack.config.js
这里是webpack.config.js
{
test: /.(JPG|gif|svg|gif|png)(?v=[0-9].[0-9].[0-9])?$/,
type: 'asset/resource',
generator: {
filename: 'assets/images/[name].[contenthash:7][ext]'
},
use: [{loader: 'url-loader'}]
},
和main.css
.b-promo {
background: url(../assets/images/bg.png) top no-repeat;
background-size: cover
}
错误消息
ERROR in ./assets/css/main.css
Module build failed (from ../node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ../node_modules/css-loader/dist/cjs.js):
Error: Can't resolve '../assets/images/bg.png' in '/home/path/to/project/src/assets/css'
似乎url()应该接受字符串作为参数,参见这里
所以尝试在main.css(并确保从main.css到bg.png文件的相对路径是正确的):
.b-promo {
background: url("../assets/images/bg.png") top no-repeat;
background-size: cover;
}