webpack3 插件之html-webpack-plugin

html-webpack-plugin 是什么?

html-webpack-plugin是webpack(??不知道请自行百度哦)的一个自动生成html文件的插件

为什么要用它?

没用 html-webpack-plugin插件之前,我们用一个js文件,需要经过webpack打包之后,手动创建一个html文件,并在html文件中用script标签引用我们之前经过webpack打包好的js文件。
用了这个插件之后,插件会自动生成html文件并将打包好的js插入文件

安装

npm install html-webpack-plugin --save

我的 webpack.config.js文件

var webpack=require('webpack');
//引用插件
var HtmlwebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    app:'./src/app.js',
    pay:'./src/pay/app.js'
  },
  output: {
    path: './build',
    filename: 'js/[name].js'
  }
}

HtmlwebpackPlugin配置项之生成html文件

plugins:[
    new HtmlwebpackPlugin(),
]
  • 说明: 当直接如上面调用,则直接会生成一个名为 index.html的文件在 webpack.config.js文件中定义的 output.path这个目录下,并且会直接吧 entry 中定义的入口文件插入html中,生成代码如下


  
    
    Webpack App
  
  
  
  
  

HtmlwebpackPlugin之生成指定标题和名字的html文件

plugins:[ 
  new HtmlwebpackPlugin({
      title: 'Hello world',
      filename: 'my_diy.html',
    })
]
  • 说明: 当直接如上面调用,则直接会生成一个名为 my_diy.html的文件在 webpack.config.js文件中定义的 output.path这个目录下,并且会直接吧 entry 中定义的入口文件插入my_diy.html中,生成代码如下


  
    
    Hello world
  
  
  
  
  

HtmlwebpackPlugin之 只插入必要的js片段(chunk 即 entry 中定义的入口文件)到生成的HTML文件

plugins:[
    new HtmlwebpackPlugin({
      chunks:["app"],
      title: 'app页面',
      filename: 'app.html'
    })
]
  • 说明: 当指定了chunks属性,webpack会按照这个属性定义的数组,将数组中所有片段完成打包,并用script标签将打包的js插入到生成的页面中,没有在数组中的片段,则不插入页面,生成代码如下


  
    
    app页面
  
  
  
  

HtmlwebpackPlugin之生成多个HTML文件

  plugins:[
    new HtmlwebpackPlugin({
      chunks:["app"],
      title: 'app页面',
      filename: 'app.html'
    }),
    new HtmlwebpackPlugin({
      chunks:["pay"],
      title: 'pay页面',
      filename: 'pay.html'
    })
]

HtmlwebpackPlugin配置项之根据已有的html文件生成html文件

有时候,插件自动生成的html文件,并不是我们需要结构,我们需要给它指定一个模板,让插件根据我们给的模板生成html

plugins:[
    new HtmlwebpackPlugin({
      chunks:["app"],
      title: 'Hello babel-loader',
      filename: 'index.html',
      template: './src/index.html',//html文件的模板
    }),

HtmlwebpackPlugin之其他配置项说明

  • inject 值{true | 'head' | 'body' | false} 注入所有的资源到特定的 template 或者 templateContent 中,如果设置为 true 或者 body,所有的 javascript 资源将被放置到 body 元素的底部,'head' 将放置到 head 元素中。
  plugins:[
    new HtmlwebpackPlugin({
      chunks:["app"],
      title: 'app页面',
      filename: 'app.html',
      inject: true,
    })
]
  • favicon 添加特定的 favicon 路径到输出的 HTML 文件中
  • hash 值{布尔型} 是否为静态资源生成hash值 一般设置为允许(true)
//生成hash值是非常必要的,我们js都是有缓存的,你懂的



  
    
    app页面
  
  
  
  

  • minify 值对象类型 压缩html文件
  plugins:[
    new HtmlwebpackPlugin({
      chunks:["app"],
      title: 'app页面',
      filename: 'app.html',
      inject: true,
      minify:{    //压缩HTML文件
         removeComments:true,    //移除HTML中的注释
         collapseWhitespace:true    //删除空白符与换行符
      }
    }),

你可能感兴趣的:(webpack3 插件之html-webpack-plugin)