错误信息:
目录结构:
HTML文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>webpack5</title>
</head>
<body>
<script src="../src/index.js"></script>
</body>
</html>
webpack.config.js:
const path = require('path')
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, 'dist'),
filename: "js/index.js",
publicPath: './',
},
module: {
rules: [
{
test: /\.css$/,
use: [{ loader: "style-loader" },
{ loader: "css-loader"}
]
},
{
test: /\.(jpg|png|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8 * 1024,
esModule: false,
name: '[hash:10].[ext]',
outputPath: "/assets/images",
}
}, {
loader: 'file-loader'
}
]
},
{
test: /\.html$/,
loader: 'html-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'test',
template: path.join(__dirname, 'publice/index.html'),
filename: "index.html",
chunk: ['index'],
hash: true
})
]
}
解决办法:
注释掉一下引入
问题原因:
- 在之前的操作中,未使用html-webpack-plugin 插件打包输出HTML,测试的时候仍旧是在原来的index.html文件中运行检测,因此不报错;
- webpack打包顺序:通过入口文件开始打包,html-loader解析HTML文件中的图片文件,style-loader、css-loader处理样式文件,url-loader解析样式中的图片路径问题,file-laoder处理其他文件格式,Plugins中的html-webpack-plugin==则负责打包HTML文件;
- html-loader 解析的是原HTML文件中的图片文件,因此原HTML文件中引入的script标签无法解析,就会报错;
- 使用了 html-webpack-plugin打包工具之后,webpack配置打包的时候,就会报错,html- webpack-plugin的本质是创建一个空的HTML文件,找到template下的文件复制到这个空的 HTML文件中,再将打包好的其他资源全部引入这个空的HTML文件。