因为打包时生成的css样式文件和js脚本文件会采用hash值做为文件命名的一部分,每一次调试打包结果都须要手动修更名称,这种作法就违背了webpack的自动化打包的初衷,并且还有需求就是要对html文件进行优化压缩,也不能直接在源文件上进行操做,还有清除注释等一系列操做。css
npm install html-webpack-plugin --save-dev
更详细的教程文档能够参考npm插件文档:https://www.npmjs.com/package/html-webpack-pluginhtml
1 var HtmlWebpackPlugin = require('html-webpack-plugin'); 2 module.exports = { 3 plugins: [ 4 //生成html文件 5 new HtmlWebpackPlugin({ 6 filename:'index.html',//生成的文件名 7 template:'./index.html',//指定打包压缩的文件 8 minify:{ 9 removeComments:true,//清除注释 10 collapseWhitespace:true//清理空格 11 } 12 }) 13 }
固然也能够同时处理多个html文件(经过chunks属性):webpack
1 plugins: [ 2 new HtmlWebpackPlugin({ 3 chunks: ['app'] 4 }) 5 ]
clean-webpack-plugin插件是用来清理构建文件夹,将上一次构建的文件所有清除,这个插件很简单,只须要plugins中引入就能够,没有什么多余的配置,可是须要注意的是在建立变量的时候须要使用大括号将变量名包裹起来,否则有时会出现报错状况,缘由尚不明确:web
1 const {CleanWebpackPlugin} = require('clean-webpack-plugin'); 2 module.exports = { 3 plugins: [ 4 new CleanWebpackPlugin()//清理构建文件夹 5 ] 6 }
这边博客是基于上一篇博客的基础上测试的,全部测试代码与上一篇博客一致,只有配置文件增长了一些新的功能,下面贴上所有配置文件代码:npm
1 var path = require("path"); 2 const glob = require('glob'); 3 const PurifyCSSPlugin = require('purifycss-webpack'); 4 var MiniCssExtractPlugin = require("mini-css-extract-plugin"); 5 var HtmlWebpackPlugin = require('html-webpack-plugin'); 6 const {CleanWebpackPlugin} = require('clean-webpack-plugin'); 7 module.exports = { 8 entry: { 9 index: './src/index.js', 10 }, 11 output: { 12 path: path.resolve(__dirname, "dist"), 13 filename: "[name]-[hash:5].js", 14 // publicPath:'/dist' 15 }, 16 module: { 17 rules: [ 18 { 19 test: /\.less$/, 20 use: [ 21 // {loader:'style-loader'}, 22 { loader: MiniCssExtractPlugin.loader }, 23 { loader: 'css-loader' }, 24 { 25 loader: 'postcss-loader', 26 options: { 27 ident: 'postcss', 28 plugins: [ 29 // require('autoprefixer')(),//添加前缀 30 require('postcss-cssnext')(),//添加前缀 转换css将来语法 31 require('cssnano')({ 32 preset: 'default' 33 }), 34 ] 35 } 36 }, 37 { loader: 'less-loader' }], 38 } 39 ] 40 }, 41 plugins: [ 42 new MiniCssExtractPlugin({ 43 // Options similar to the same options in webpackOptions.output 44 // both options are optional 45 filename: "[name]-[hash:5].css", 46 // chunkFilename: "[id].css" 47 }), 48 new HtmlWebpackPlugin({ 49 filename:'index.html',//生成的文件名 50 template:'./index.html',//打包压缩的文件 51 minify:{ 52 removeComments:true,//清除注释 53 collapseWhitespace:true//清理空格 54 } 55 }), 56 new CleanWebpackPlugin() 57 // new PurifyCSSPlugin({ 58 // paths:glob.sync(path.join(__dirname,'../index.html')) 59 // }) 60 ] 61 }