开始之前,先看如下事例:
const HtmlWebpackPlugin = require('html-webpack-plugin')const path = require('path');module.exports = { entry: { // index: './src/index.js', // utils: './src/utils.js' index: path.resolve(__dirname, 'src/index.js'), utils: path.resolve(__dirname, 'src/utils.js') }, output: { //path: __dirname + '/dist', //filename: '[name]-[chunkhash].js' path: path.resolve(__dirname, 'dist'), filename: '[name]_bundle.js' //配合下面配置中的hash选项使用,可不加[chunkhash] }, plugins: [ new HtmlWebpackPlugin({ title: 'My Test', filename: 'test.html', hash: true, chunks: ['utils'] }), new HtmlWebpackPlugin({ title: 'My App', filename: 'index.html', hash: true, chunks: ['index'] }) ]}复制代码
常用的配置属性
template
指定你生成的文件所依赖哪一个html文件模板,模板类型可以是handlebars、html、jade、ejs等。但是要注意的是,如果想使用自定义的模板文件的时候,你需要安装对应的loader
哦。
$ npm install handlebars-loader --save-dev复制代码
//webpack.config.jsrules: [ { test: /\.hbs$/, loader: 'handlebars-loader' }, ...]plugins: [ new HtmlWebpackPlugin({ ... template: './src/pages/index/index.hbs', })]复制代码
minify
使用minify会对生成的html文件进行压缩。默认是false。html-webpack-plugin内部集成了 html-minifier,因此,还可以对minify进行配置:(注意,虽然minify支持BooleanObject,但是不能直接这样写:minify: true , 这样会报错 ERROR in TypeError: Cannot use 'in' operator to search for 'html5' in true
, 使用时候必须给定一个 { }
对象 )
...plugins: [ new HtmlWebpackPlugin({ ... minify: { removeAttributeQuotes: true // 移除属性的引号 } })]复制代码
chunks
chunks主要用于多入口文件,当你有多个入口文件,那就回编译后生成多个打包后的文件,那么chunks 就能选择你要使用那些js文件
entry: { index: path.resolve(__dirname, './src/index.js'), devor: path.resolve(__dirname, './src/devor.js'), main: path.resolve(__dirname, './src/main.js')}plugins: [ new httpWebpackPlugin({ chunks: ['index','main'] })]复制代码
那么编译后:
复制代码
- 如果你没有设置chunks选项,那么默认是全部显示
excludeChunks
排除掉一些js
//与上面写法等价excludeChunks: ['devor.js']复制代码
更多配置信息可参考: