一概述
- html-webpack-plugin插件介绍
- html-webpack-plugin插件安装与配置
- html-webpack-plugin插件的特性
二html-webpack-plugin插件介绍
- webpack中的HTML插件(类似于一个模板引擎插件)
- 可以通过此插件自定制Index.html页面的内容
三html-webpack-plugin插件安装与配置
3.1html-webpack-plugin插件安装
通过如下的命令,即可在项目中安装此插件
npminstallhtml-webpack-plugin-D
安装完成后package.json->devDependencies下可以看到html-webpack-plugin依赖
"devDependencies":{"html-webpack-plugin":"^5.5.0","webpack":"^5.74.0","webpack-cli":"^4.10.0","webpack-dev-server":"^4.11.1"},
3.2html-webpack-plugin插件配置
1-导入HTML插件,得到一个构造函数
constHtmlPlugin=require('html-webpack-plugin')
2-指定源文件和生成文件的存放路径
consthtmlPlugin=newHtmlPlugin({template:'./src/index.html',//指定源文件的存放路径filename:'./index.html',//指定生成文件的存放路径})
3-通过plugins节点,使htmlPlugin插件生效
module.exports={entry:path.join(__dirname,'./src/index.js'),//打包入口文件的路径output:{path:path.join(__dirname,'./dist'),//输出文件的存放路径filename:'bundle.js',//输出文件的名称},mode:'development',//mode用来指定构建模式。可选值有development和productiondevServer:{open:true,host:'localhost',port:8080,static:{directory:path.join(__dirname,'./')},},plugins:[htmlPlugin],//通过plugins节点,使htmlPlugin插件生效}
3.3使用html-webpack-plugin前后对比
说明:
- 使用前,未配置html源和目的路径,打开后是根目录
- 使用后,配置了html源和目的路径,可以预览效果图
四html-webpack-plugin插件的特性
4.1index源码和html-webpack-plugin生成对比
4.2解惑hmtl-webpack-plugin
- 通过HTML插件复制到项目根目录中的Index.html页面,也被放到内存中
- HTML插件在生成的index页面,自动注入了打包的bundle.js文件
五参考
Webpack-全局exports