html-webpack-plugin

开始之前,先看如下事例:

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.js
rules: [
      {
        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']
    })
]
复制代码

那么编译后:

<script type=text/javascript src="index.js"></script>
<script type=text/javascript src="main.js"></script>
复制代码
  • 如果你没有设置chunks选项,那么默认是全部显示

excludeChunks

排除掉一些js

//与上面写法等价
excludeChunks: ['devor.js']
复制代码

更多配置信息可参考: www.npmjs.com/package/htm…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值