打包后自动生成html [html-webpack-plugin插件]
注意: 本进阶在webpack进阶【3】的基础上进行
一、为什么需要html-webpack-plugin插件
-
如果没有用插件,index.html中我们需要引入打包后的js文件,以后更多还需要引入css文件。
image.png
-
-
index.html引用的文件名要和webpack.config.js中output中fileName中的文件名要相同。
image.png
-
- 如果webpack.config.js中output中的fileName文件名修改了,index.html中引入的文件名也需要修改。
- 所以这时候我们需要引用 【html-webpack-plugin插件】,打包的时候【dist文件夹】自动生成【index.html】文件,并且会【index.html】会自动引入打包后的【js】。
二、下载插件【html-webpak-plugin】
cnpm i html-webpack-plugin
三、webpack.config.js 中引入 html-webpack-plugin 插件并进行配置
const path = require('path'); // 引入path模块
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 引入自动生成 html 的插件
// 配置webpack的配置文件,需要将配置的对象导出,给webpack使用
module.exports = {
// 1. 打包入口,从哪个文件开始打包
entry: './src/main.js',
// 2. 打包的文件放在哪
output:{
// 打包的文件输出的目录(输出的目录必须是一个绝对路径),这里也可以写成path:path.join(_dirname, 'dist')
path: path.join(__dirname, './dist'),
// 打包后的文件名叫什么
filename: 'bundle.js'
},
// 3. 打包的模式: production 生产模式(打包后的文件或压缩) development(开发模式,不压缩)
mode: 'development',
// 4. 插件配置
plugins: [
// 我们要把哪个目录下的 html 进行自动生成。
new HtmlWebpackPlugin({template: './public/index.html'})
],
}
四、执行打包命令
cnpm run build
五、打包后,dist中有html文件和js文件
![](https://img.haomeiwen.com/i15765796/5651d7a08d5999b1.png)
网友评论