JS、HTML、CSS 压缩

JS 压缩

webapck 4 内置 terser-webpack-pluginmode: 'production' 则开启。

webpack 3 以及之前则内置 uglifyjs-webpack-plugin(现已不维护)。

CSS 压缩

使用 optimize-css-assets-webpack-plugin

同时使用 csshano

// webpack.config.js
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')

module.exports = {
  //...
  plugins: [
    new OptimizeCSSAssetsPlugin({
      assetNameRegExp: /\\\\.css$/g,
      cssProcessor: require('cssnano'),
    })
  ]
}

HTML 压缩

修改 html-webpack-plugin,设置压缩参数

// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  //...
  plugins: [
    new HtmlWebpackPlugin({
      // 模版路径
      template: path.join(__dirname, 'src/index.html'),
      // 将 HTML 写入的文件,默认为 index.html
      filename: 'index.html',
      // 对应 entry 中的键,希望哪个 chunk 注入就写哪个
      chunks: ['index'],
      // 将资源注入给定的 template,默认 true
      inject: true,
      // 压缩输出,默认 true
      minify: {
        html5: true, // 根据 HTML5 规范解析输入
        collapseWhitespace: true, // 删除空白
        preserveLineBreaks: false, // 删除换行符
        minifyCSS: true, // 压缩 CSS
        minifyJS: true, // 压缩 JS
        removeComments: false, // 删除 HTML 注释
      },
    })
  ]
}

区别

html-webpack-plugin 里面的 minify 的 minifyCSS 参数和 minifyJS 参数用于压缩一开始就内联在 HTML 里面的 CSS 和 JS,不是打包生成的 CSS 和 JS。