设置 HtmlWebpackPlugin

首先安装插件

1
npm install html-webpack-plugin --save-dev

编辑 webpakc.config.js

1
2
3
4
5
6
7
8
9
10
11
// add
const HtmlWebpackPlugin = require("html-webpack-plugin");

// add
plugins: [
new HtmlWebpackPlugin({
// 选取 './src/index.html' 文件
template: "./src/index.html",
}),
],

img

我们可以先删除 dist 文件,然后执行npm run build
可以看到重新生成了 dist 文件夹,此时文件结构为

1
2
3
4
5
6
7
8
9
10
11
webpack
|- /dist
|-index.bundle.js
|-index.html
|- /node_modules;
|- /src
|- index.html
|- index.js
|- package-lock.json
|- package.json;
|- webpack.config.js

在浏览器中打开dist文件夹中的index.html
我们可以在页面中看到我们hello webpack,并且控制台中有输出hello webpack
img

但是其实我们之前的index.html并没有引入index.js,但HtmlWebpackPlugin会帮我们引入自动引入
去查看打包后的index.html可以找到

1
<script defer="defer" src="index.bundle.js">