这个插件的两个作用:
为html文件中引入的外部资源如script、link动态添加每次compile后的hash,防止引用缓存的外部文件问题
可以生成创建html入口文件,比如单页面可以生成一个html文件入口,配置N个html-webpack-plugin可以生成N个页面入口
安装使用如下:
一、首先安装html-webpack-plugin插件
在cmd中打开项目,输入cnpm install html-webpack-plugin;
二、在webpack-config.js的plugins里面添加 信息,如下图
然后在cmd中输入,webpack,即可以在项目文件夹下自动生成index.html。如果报错,则表示,未安装html-webpack-plugin插件。
注:不配置任何选项的html-webpack-plugin插件,他会默认将webpack中的entry配置所有入口thunk和extract-text-webpack-plugin抽取的css样式都插入到文件指定的位置。
三、多页面配置
对于生成多页面的情况,在plugins配置多个plugin即可
1 plugins:[
2 new webpack.BannerPlugin(‘测试webpack搭建 ‘),
3 new HtmlWebpackPlugin(),
4 new HtmlWebpackPlugin({
5 title:‘测试webpack‘,
6 template: ‘src/template/index.html‘, // 源模板文件
7 filename: ‘ // 输出文件【注意:这里的根路径是module.exports.output.path】
8 showErrors: true,
9 inject: ‘body‘,
10 chunks: ["index"],
11 favicon:"",
12 hash:true,
13 minify:{
14 caseSensitive: false, //是否大小写敏感
15 removeComments:true, // 去除注释
16 removeEmptyAttributes:true, // 去除空属性
17 collapseWhitespace: true //是否去除空格
18 }
19 }),
20 new HtmlWebpackPlugin({
21 title:‘测试webpack‘,
22 template: ‘src/template/index.html‘, // 源模板文件
23 filename: ‘ // 输出文件【注意:这里的根路径是module.exports.output.path】
24 showErrors: true,
25 inject: ‘body‘
26 })
27 ]
多页面配置
四、使用template模板页面
增加模板页面
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title><%= htmlWebpackPlugin.options.title %></title>
6 <% for (var css in htmlWebpackPlugin.files.css) { %>
7 <link href="<%=htmlWebpackPlugin.files.css[css] %>" rel="stylesheet">
8 <% } %>
9 </head>
10 <body>
11 <!-- 测试 -->
12 <div id="app" style=""></div>
13 </body>
14 <script type="text/babel">
15 </script>
16 </html>
模板页面
在配置中配置模板页面
五、自定义增加的js文件
在配置文件中,chunks选项添加对应的内容即可。
对应的内容为entry中的属性。具体如下图
六、生成页面压缩
配置minify配置项,常用的几个配置见上图
七、其他配置项解释如下
title: 生成的HTML模板的title,如果模板中有设置title的名字,则会忽略这里的设置
如果您觉得本文的内容对您的学习有所帮助:
关键字:
jquery