问题描述
我正在使用带有 html-webpack-plugin
的模板文件。到目前为止,我在模板中为我的图像使用了 img
标签,file-loader
已经很好地处理了它们。但是,如果我尝试内联设置元素的背景图像,则不会触发 file-loader
并且图像不会移动到我的构建文件夹中。
有问题的模板文件:
<div class="slide" style="background-image: url('assets/imgs/Portfolio/AFTO.png')"></div> // This image is not loaded
<div class="slide">
<img src="assets/imgs/Portfolio/BTB.png" alt=""> // This image is loaded fine,hash and all
</div>
webpack 配置:
const webpack = require('webpack'),path = require("path"),fs = require("fs"),Inject = require('webpack-inject-plugin').default,{ ENTRY_ORDER } = require('webpack-inject-plugin'),HtmlWebpack = require('html-webpack-plugin'),{ CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: "development",devtool: "inline-source-map",entry: path.resolve(__dirname,'./js/app.js'),output: {
filename: "app.[contentHash].js",path: path.resolve(__dirname,"./build")
},devServer: {
contentBase: './build'
},module: {
rules: [
{
test: /\.m?js$/,use: {
loader: 'babel-loader',options: {
presets: ['@babel/preset-env']
}
}
},{
test: /\.scss$/,use: ['style-loader','css-loader','sass-loader']
},{
test: /\.html$/,use: ['html-loader']
},{
test: /\.(png|gif|jpeg|jpg|svg)$/,use: {
loader: 'file-loader',options: {
name: '[name].[hash].[ext]',outputPath: 'imgs'
}
}
},{
test: /\.(woff|eot|ttf)$/,outputPath: 'fonts'
}
}
}
]
},plugins: [
new webpack.ProvidePlugin({
// global utils
$: 'jquery',jQuery: 'jquery'
}),new Inject(() => fs.readFileSync('./js/vendor/t.js-master/t.js',{encoding: 'utf-8'}),{
entryOrder: ENTRY_ORDER.Last
}),new HtmlWebpack({
template: 'template.html'
}),new CleanWebpackPlugin({ cleanStaleWebpackAssets: false })
]
}
我对此感到惊讶,因为我认为 webpack 查找文件的 url,而不是 html 标签。有解决方法吗?谢谢。
解决方法
我认为有一种方法可以实现您的目标,只需使用 html-webpack-plugin
的插值语法,而不必使用 html-loader
(可能会发生冲突)。
以下是几个步骤:
- 更改您的模板以使用插值语法来要求图像:
<div style="background-image: url(<%= require('assets/imgs/Portfolio/AFTO.png') %>" />
- 禁用
esModule
的file-loader
选项以使require
函数工作而无需.default
:
webpack.config.js
{
loader: 'file-loader',options: {
// ...
esModule: false,}
}
- 最后,我们可能需要删除
html-loader
以避免未编译插值语法