作用
由于每次生成的index.html还需要手动写死引入打包后的Js文件,并且html文件没有被压缩,所以需要使用此插件
使用
安装:npm i html-webpack-plugin -D
新建目录public,里面放入Index.html 在webpackbase设置里设置插件:
const dev = require ( './webpack.dev' ) ;
const prod = require ( './webpack.prod' ) ;
const path = require ( 'path' ) ;
const merge = require ( 'webpack-merge' ) ;
const HtmlWebpackPlugin= require ( 'html-webpack-plugin' ) ;
module. exports = ( env) => {
let isdev = env. development;
const base = {
entry: path. resolve ( __dirname, '../src/index.js' ) ,
output: {
filename: 'bundle.js' ,
path: path. resolve ( __dirname, '../dist' )
} ,
plugins: [
new HtmlWebpackPlugin ( {
template: path. resolve ( __dirname, '../public/index.html' ) ,
filename: 'index.html' ,
minify: ! isdev && {
removeAttributeQuotes: true ,
collapseWhitespace: true
}
} )
]
}
if ( isdev) {
return merge ( base, dev) ;
} else {
return merge ( base, prod) ;
}
}
然后使用命令去生成生产的代码,可以发现dist目录下的index.html自动加上了bundle.js而且被压缩成一行。 注意如果模板啥都没改打包后的index.html只会有一条引入标签。