文章目录
一、文章参考
二、问题描述
每次使用webpack打包,都要手动创建静态的html 代码,然后引用打包后的JS文件,操作很繁琐
三、html-webpack-plugin 介绍
- 每次打包完成之后,会自动帮我们创建一个HTML文件,HTML文件会自动引入打包好的js
- 如果每次打包的版本号不一致,则这个插件的就尤为重要,不需要每次因版本号的改变而手动去改HTML代码
3.1 安装插件
cnpm i --save-dev html-webpack-plugin
3.2 webpack.config.js 默认配置
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: 'index.js',
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin()
]
}
四、参数配置说明
{
plugins: [
new CleanWebpackPlugin(), //删除上次打包文件,默认目录'./dist'
new HtmlWebpackPlugin({ // 打包输出HTML
title: '测试htmlWebpackPlugin',
minify: { // 压缩HTML文件
removeAttributeQuotes: true, // 移除属性的引号
removeComments: true, // 移除HTML中的注释
collapseWhitespace: true, // 删除空白符与换行符
minifyCSS: true// 压缩内联css
},
inject: true, // true 或body 默认值,script标签位于html文件的 body 底部; head script 标签位于 head 标签内
hash: true, // 引入 js 文件后面紧跟一个独特的 hash 值
// filename: 'huangbiao.html', // 文件名
filename:'huangbiao-[hash].html', // 带hash 值的文件名
// chunks {?} ? Allows you to add only some chunks (e.g only the unit-test chunk)
template: './src/template/index.html' // 模板地址
})
],
}
4.1 hash
hash选项的作用是 给生成的 js 文件一个独特的 hash 值,该 hash 值是该次 webpack 编译的 hash 值。默认值为 false 。
<script type="text/javascript" src="main.js?3f4e4073766b59c367d4"></script>
4.2 HTML如何让 title 变为配置的信息
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
</body>
</html>
<%= htmlWebpackPlugin.options.title %> 显示标题,后面会强调,这种情况是在没有使用
templateParameters
属性的情况下可以使用
4.3 inject
注入选项。有四个选项值 true, body, head, false.
- true 默认值,script标签位于html文件的 body 底部
- body 同 true
- head script 标签位于 head 标签内
- false 不插入生成的 js 文件,只是单纯的生成一个 html 文件
4.4 参数说明表
名称 | 类型 | 默认 | 描述 |
---|---|---|---|
title | {string} | Webpack App | 用于生成HTML文档的标题 |
filename | {string} | index.html | 要将HTML写入的文件,默认为index.html,在这里可以指定一个目录(、asset/index.html) |
template | {string} | " | webpack模板的相对或绝对路径。默认情况下,src/index.ejs如果它存在,它将使用 |
inject | {Boolean | String} | true |
favicon | {String} | " | 将给定的favicon路径添加到输出HTML |
templateParameters | {Boolean | Object | Function |
meta | {Obeject} | {} | 允许注入meta-tags。例如meta:{viewport:’ width=device-width,initial-scale=1,shrik-to-fit=no '} |
base | { Object } | String | false |
minify | {Boolean} | Object | true如果mode是’ production ',否则false |
hash | {Boolean} | false | 如果为true,将唯一的Webpack编译哈希附加到所有包含的脚本和CSS文件,对于清除缓存很有用 |
cache | {Boolean} | true | 仅在文件被更改时才发出文件 |
showErrors | { Boolean } | true | 将错误详细信息写入HTML页面 |
chunks | { ? } | ? | 允许您仅添加一些块{ 例如,仅添加一些单元测试块 } |
chunksSortMode | { String | Function } | auto |
excludeChunks | { Array .} | " | 允许您跳过一些块(例如,不添加单元测试块) |
xhtml | { Boolean } | false | 如果true将link标记渲染为自动关闭(符合XHTML) |
五、HtmlWebpackPlugin给模板添加参数 templateParameters
5.1 页面代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title><%= title %></title>
</head>
<body>
<div id="root"></div>
<div class="webpackStudy">
<div class="huangbiao">
<div><%= myName %></div>
<div class="huanghaili">
<div><%= sonName %></div>
</div>
</div>
<div class="">
<li class="dib">
<span class="icon iconfont"></span>
<div class="name">icon-normalization</div>
<div class="code-name">&#xe62b;</div>
</li>
<li class="dib">
<span class="icon iconfont"></span>
<div class="name">icon-gongyinglian</div>
<div class="code-name">&#xe640;</div>
</li>
</div>
</div>
</body>
</html>
使用
<%=变量名%>
显示变量
5.2 HtmlWebpackPlugin 配置
{
plugins: [
new HtmlWebpackPlugin({
// 打包输出HTML
title: "测试htmlWebpackPlugin",
minify: {
// 压缩HTML文件
removeAttributeQuotes: true, // 移除属性的引号
removeComments: true, // 移除HTML中的注释
collapseWhitespace: true, // 删除空白符与换行符
minifyCSS: true // 压缩内联css
},
templateParameters: (compilation, assets, assetTags, options) => {
console.log(arguments)
return {
title: "测试htmlWebpackPlugin",
myName: 'huang-biao',
sonName:'huang-haili'
}
},
inject: true, // true 或body 默认值,script标签位于html文件的 body 底部; head script 标签位于 head 标签内
hash: true, // 引入 js 文件后面紧跟一个独特的 hash 值
filename: "index.html", // 文件名
// filename: 'huangbiao.html', // 文件名
// filename:'huangbiao-[hash].html', // 带hash 值的文件名
template: "./src/template/index.html" // 模板地址
}),
],
}
templateParameters 定义参数变量值
ReferenceError: htmlWebpackPlugin is not defined错误
提示上述这个错误原因是因为 html 页面中使用了
<%= htmlWebpackPlugin.options.title %>
变量,删除该变量即可
- 如果定义了 templateParameters 自定义参数,则在html页面中,可以使用
<%=变量名%>
显示变量 页面则不能使用<%= htmlWebpackPlugin.options.title %>
显示标题了,可以使用变量替换
六、多页面配置
6.1 webpack 配置说明
const{resolve}=require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports={
entry:{
vender:['./src/js/jquery.js','./src/js/common.js'],
index:'./src/js/index.js',
cart:'./src/js/cart.js'
},
output:{
path:resolve(__dirname,'build'),
filename:'[name].js'
},
mode:'development',
module:{
rules:[]
},
plugins:[//这里需要打包两个html,所以有两个HtmlWebpackPlugin对象各自进行配置
new HtmlWebpackPlugin({
template:'./src/index.html',
filename:'index.html',
chunks:['vender','index']//配置html需要引入的chunk,index 是 entry中的key
}),
new HtmlWebpackPlugin({
template:'./src/cart.html',
filename:'cart.html',
chunks:['vender','cart']//配置html需要引入的chunk,cart 是 entry中的key
}),
]
}
6.2 动态生成多文件
const glob = require("glob")
const pageMain = './src/pages/**?/main.js'
const pageRouter = require('../src/corejs/pageRouter.json').routes.map(page => page.name)
// const pageRouter = ['index', 'unitManageSystem']
const entryRouter = glob.sync(pageMain).map(entry => entry)
// const entryRouter = [
// './src/pages/index/main.js',
// './src/pages/login/main.js',
// './src/pages/unitManageSystem/main.js'
// ]
const entry = {}
pageRouter.forEach(page => {
entry[page] = entryRouter[entryRouter.findIndex(router => router.includes(page)) || 0]
})
// entry = {
// index: './src/pages/index/main.js',
// unitManageSystem: './src/pages/unitManageSystem/main.js'
// }
const htmlWebpackPlugin = pageRouter.map(page => new HtmlWebpackPlugin({
filename: `${page}.html`,
template: path.resolve(rootPath, "src/html.tmpl"),
favicon: path.resolve(rootPath, "src/logo.ico"),
chunks: [`${page}`], // 指定打包生成的js作为对应的html页面引入
inject: true
}))