这是我第一次在这里写作,请谅解。我第一次在项目中使用webpack,并且遇到了一个问题,我试图在我的sass文件中使用background url()函数设置背景图片,例如:
.img-container {
background: url('../../img/homepage-login-prog.jpg') no-repeat center center fixed;
background-size: cover;
}
我的文件夹结构如下:
- css
| app.css
- dist (this folder is created after building for production)
- img
| some-image.jpg
- js
| app.js (entry point for webpack output,
this is where I import main.scss file)
- js-vendor
| vendor.js (third-party libraries like bootstrap, jquery)
- sass (this is where I keep all my sass files which get compiled using
webpack loaders)
| components
| greetings-section.scss
| navbar.scss
| main.scss
| variables.scss
- template.html
- webpack.common.js
- webpack.dev.js
- webpack.prod.js
因为我已经针对开发和生产环境配置了webpack,所以我有两个不同的文件,一个用于开发环境,一个用于生产环境,它们都继承于通用配置文件。通用配置文件的内容如下:
const path = require("path");
module.exports = {
entry:{
main: "./js/app.js",
vendor: "./js-vendor/vendor.js"
},
module: {
rules: [
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(svg|png|jp(e*)g|gif)$/,
use: [{
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "img",
}
}]
}
]
}
};
我的webpack开发配置如下:
const common = require("./webpack.common");
const merge = require("webpack-merge");
const path = require("path");
var HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = merge(common, {
mode: "development",
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist")
},
plugins: [
new HtmlWebpackPlugin({
template: "./template.html"
}),
new MiniCssExtractPlugin({
filename: "[name].[contentHash].min.css"
}),
],
module: {
rules: [
{
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: "../../"
}
},
"css-loader",
"sass-loader"
]
}
]
}
});
所以,在webpack-dev-server启动后,它会弹出一个错误:
ERROR in ./sass/main.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/lib/loader.js!./sass/main.scss)
Module not found: Error: Can't resolve '../../img/homepage-login-prog.jpg' in 'C:\Users\...\...\...\sass'
您可以看到,我已经尝试使用mini-css-extract-plugin中的publicPath选项设置相对路径,但这对我没有用。
我还阅读了其他人遇到类似问题的文章,但他们的解决方案都不适用于我。因此,我想问的是,有人知道如何配置webpack来识别我的sass文件中图像的url并正确绑定它吗?
很抱歉发了一篇长帖子,非常感谢任何帮助。