上一节的入门中,只是跑通了一个很简单的webpack项目的流程,对其中的参数以及实战运用中的一些用法并不太清楚,虽然目前工做项目中并无用起webpack,不过以为仍是须要再去摸索一番,以即可以更清楚的用起这个工具。javascript
上一节最终运行webpack命令,会在dist目录下生成一个js文件,这时候新建一个index.html文件并引入这个js:html
index.htmljava
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>This is a test</title> </head> <body> <div id="test">Start:</div> <script src="bundle.f9be197eff25e8667c8c.js"></script> </body> </html>
这中间的f9be197eff25e8667c8c
就是上一次运行webpack命令时生成的hash值,若是每次对js改动,而后运行webpack
命令,都会引发hash值的变化,也就是说每次都得在index.html
中改变引入js的名称,这样显然不合理,这时候能够引入一些插件来进行一些流程上的优化。webpack
html-webpack-plugin
能够根据你设置的模板,在每次运行后生成对应的模板文件,同时所依赖的CSS/JS也都会被引入,若是CSS/JS中含有hash值,则html-webpack-plugin
生成的模板文件也会引入正确版本的CSS/JS文件。git
npm install html-webpack-plugin --save-dev
在webpack.config.js中引入:github
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = { entry: './app/index.js', output: { ... }, module: { ... }, plugins: [ new HtmlWebpackPlugin({ title: "This is the result", filename: "./index.html", template: "./app/index.html", inject: "body", favicon: "", minify: { caseSensitive: false, collapseBooleanAttributes: true, collapseWhitespace: true }, hash: true, cache: true, showErrors: true, chunks: "", chunksSortMode: "auto", excludeChunks: "", xhtml: false }) ] };
而后看一下这些参数的意义:web
title: 生成的HTML模板的title,若是模板中有设置title的名字,则会忽略这里的设置npm
filename: 生成的模板文件的名字segmentfault
template: 模板来源文件缓存
inject: 引入模块的注入位置;取值有true/false/body/head
favicon: 指定页面图标;
minify: 是html-webpack-plugin
中集成的 html-minifier
,生成模板文件压缩配置,有不少配置项,能够查看详细文档
caseSensitive: false, //是否大小写敏感 collapseBooleanAttributes: true, //是否简写boolean格式的属性如:disabled="disabled" 简写为disabled collapseWhitespace: true //是否去除空格
hash: 是否生成hash添加在引入文件地址的末尾,相似于咱们经常使用的时间戳,好比最终引入是:<script type="text/javascript" src="bundle.049424f7d7ea5fa50656.js?049424f7d7ea5fa50656"></script>
。这个能够避免缓存带来的麻烦
cache: 是否须要缓存,若是填写true,则文件只有在改变时才会从新生成
showErrors: 是否将错误信息写在页面里,默认true,出现错误信息则会包裹在一个pre
标签内添加到页面上
chunks: 引入的模块,这里指定的是entry中设置多个js时,在这里指定引入的js,若是不设置则默认所有引入
chunksSortMode: 引入模块的排序方式
excludeChunks: 排除的模块
xhtml: 生成的模板文档中标签是否自动关闭,针对xhtml的语法,会要求标签都关闭,默认false
[3]