我计划将Webpack用于一个项目,并使用Html-loader + file-loader设置工作流程,以获取带有动态src图片的html文件,如Colt Steele在{{3 }}。这是我的src /文件:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Popular on Letterboxd</title>
</head>
<body>
<img src="./assets/chira.jpg" />
</body>
</html>
index.js:
import img from './assets/chira.jpg';
import "./main.css";
和main.css
body {
background-color: darkblue;
}
这些是我的配置文件(我有一个用于开发和生产的个人,并且有一个共同的):
webpack.common.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
devtool: "none",
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
],
},
{
test: /\.html$/,
use: ["html-loader"]
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]',
publicPath: 'assets',
outputPath: 'assets/img'
}
}
]
}
],
},
};
webpack.dev.js:
const path = require('path');
const common = require("./webpack.common");
const merge = require('webpack-merge');
module.exports = merge(common, {
mode: "development",
devServer: {
contentBase: path.join(__dirname, 'src'),
},
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist")
},
});
和webpack.prod.js:
const path = require('path');
const common = require("./webpack.common");
const merge = require('webpack-merge');
module.exports = merge(common, {
mode: "production",
output: {
filename: "main.[contentHash].js",
path: path.resolve(__dirname, "dist")
},
});
但是,当我运行npm run build时,它将执行以下命令:
"build": "webpack --config webpack.prod.js"
我得到了带有资产/ img / [名称]。[哈希]。[ext]的预期dist文件夹,但是在我的index.html中,我没有得到预期的src标记:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Popular on Letterboxd</title>
</head>
<body>
<img src="[object Module]" />
<script type="text/javascript" src="main.e55bd4ff82bf2f5cec90.js"></script></body>
</html>
我已经尝试解决该问题已有一段时间了,但是我似乎在任何地方都找不到正确的答案,到目前为止,我一直没有尝试过。如果有人遇到此问题可以解决他们的问题,或者有人对问题可能是什么以及我能做什么有任何线索,我将不胜感激。预先感谢!
答案 0 :(得分:1)
如果文件加载器版本为5.0,则为。在文件加载器上添加另一个选项“ esModule:false”将解决此问题。
{
test: /\.(png|jpe?g|gif|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]',
publicPath: 'assets',
outputPath: 'assets/img',
esModule: false
}
}
]
}