在生产模式下运行Webpack时,我试图让Webpack从HTML文件加载行内背景图像。我目前正在使用文件加载器来执行此操作,但是它似乎无法正常工作。不确定为什么Webpack无法“看到”图像。
示例html背景图片
<div class="project" style="background-image: url('/src/assets/img/projects/airguitar.png')">
webpack.common.js文件
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: {
main: "./src/index.js"
},
module: {
rules: [
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs"
}
}
}
]
}
};
webpack.prod.js
const glob = require('glob');
const path = require("path");
const common = require("./webpack.common");
const merge = require("webpack-merge");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const generateHTML = () => glob.sync('./src/*.html').map(
dir => new HtmlWebpackPlugin({
favicon: "./src/assets/img/favicon.png",
filename: path.basename(dir),
template: dir,
minify: {
removeAttributeQuotes: true,
collapseWhitespace: true,
removeComments: true
}
}),
);
module.exports = merge(common, {
mode: "production",
output: {
filename: "[name].[contentHash].bundle.js",
path: path.resolve(__dirname, "dist")
},
optimization: {
minimizer: [
new OptimizeCssAssetsPlugin(),
new TerserPlugin(),
...generateHTML()
]
},
plugins: [
new MiniCssExtractPlugin({ filename: "[name].[contentHash].css" }),
new CopyPlugin([
{ from: './src/contact.php', to: '' },
{ from: './.htaccess', to: '' },
]),
new CleanWebpackPlugin()
],
module: {
rules: [
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
]
}
});