项目结构
webpackHtmlWebpackPlugin
│ package-lock.json
│ package.json
│ webpack.config.js
└─src
index.js
mine.js
安装依赖
在webapckHtmlWebpackPlugin目录下运行
npm i webpack webpack-cli htm-lwebpack-plugin --save-dev
webpack.config.js配置文件
const { resolve } = requrie("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
mode:"development",
entry:{
index:"./src/index.js",
mine:"./src/mine.js"
},
output:{
path:resolve(__dirname,"dist"),
filename:"[name].build.js"
},
plugins:[
new HtmlWebpackPlugin({
title:"index的Html文件",
chunks:["index"]
}),
new HtmlWebpackPlugin({
title:"mine的Html文件",
excludeChunks:['mine'],
template:"./public/mineTemplate.html",
filename:"mine.html"
})
]
}
webpack中的关键属性
puligns属性
这个属性接受一个数组,里面的每一项是使用插件的实例对象
html-webpack-plugin常用的option参数
- title:在不设置template属性的情况下,会将其值在自动生成html的
标签中;使用了template后,需要在模板中使用<%=htmlWebpackPlugin.options.title%>作为变量,打包后,值将替换掉<%=htmlWebpackPlugin.options.title%>,可以查看下方的mineTimeplate.html - chunks:默认值为"all",即不做设置时,将入口所有的js都引入到对应的html中,但会受到excludeChunks的影响
- excludeChunks:接受一个字符串数组,每一项字符串数组将匹配entry中的key,如果命中,则对应的html将不会加载这个js
- template:接受一个字符串路径,在打包时基于这个模板进行打包
- filename:设置打包后的html文件名,默认值为index.html;如果其中含有[name]字符串,则会根据entry的key值,生成对应key值的html
mineTemplate.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- mine设置的title值将替换掉title标签内的内容 -->
<title><%=htmlWebpackPlugin.options.title%></title>
</head>
<body></body>
</html>
打包命令
- 方式一:在webpackHtmlWebpackPlugin目录下运行
webpack --config ./webapck.config.js
- 方式二:在package.json文件的scripts属性新增如下命令
{
...
"scripts":{
"build":"webpack --config ./webpack.config.js"
}
...
}
修改保存后,在webpackHtmlWebpackPlugin目录下运行如下命令:
npm run build
打包后的目录
webpackHtmlWebpackPlugin
│ package-lock.json
│ package.json
│ webpack.config.js
├─dist
│ index.build.js
│ index.html
│ mine.build.js
│ mine.html
├─public
│ mineTemplate.html
└─src
index.js
mine.js