我是 Webpack 新手,加载图片时遇到问题。我想使用 Webpack 加载图像并在 SASS 中使用此特定图像作为背景使用 background: url('./urlToMyPic.png');
.home {
background: url("../../Background2x.png");
background-color: $dark;
height: calc(100vh - 58px);
}
我的 webpack.config.js:
// entry --> output
const path = require('path');
//way to expose an object to another file
module.exports = {
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'public')
},
mode: 'development',
module: {
rules: [{
loader: 'babel-loader',
test: /.\js$/,
exclude: /node_modules/
},
{
test: /\.s?css$/,
use: [{
loader: "style-loader"
},
{
loader: "css-loader"
},
{
loader: "sass-loader"
}
]
},
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader',
options: {}
}]
}
]
},
devtool: 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(__dirname, 'public'),
historyApiFallback: true //to allow client site routing
}
};
Sass 运行良好,Webpack 能够将 sass 转换为 css 并正确提供服务。但是,当涉及到图像时,我收到一条错误消息:
ERROR in ./node_modules/css-loader!./node_modules/sass-loade/libloader.js!./src/styles/style.scss
Module not found: Error: Can't resolve '../../Background2x.png' in '/Users/clement/Desktop/portfolio-react/src/styles'
@ ./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./src/styles/style.scss 8:507-540
@ ./src/styles/style.scss
@ ./src/app.js
@ multi (webpack)-dev-server/client?http://localhost:8080 ./src/app.js
我无法找出问题所在?你们中有人遇到过类似的问题吗? 谢谢
最佳答案
您必须为文件加载器定义输出文件名。如果您不这样做,它将不会保留与源中相同的文件名:
{
test: /\.(png|jpg|gif)$/,
use: {
loader: 'file-loader',
options: {
name: 'images/[name].[ext]',
publicPath: 'public/'
}
}
}
您可以通过手动检查您的公共(public)文件夹和检查图像名称来验证这一点。
关于javascript - 使用 Webpack 添加图像并在 sass 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581609/