vue-cli2添加compression-webpack-plugin压缩代码

1、安装compression-webpack-plugin开发依赖插件

npm install --save-dev compression-webpack-plugin

2、将productionGzip配置为true

productionGzip: true,
productionGzipExtensions: ['js', 'css'],

3、引入并配置compression-webpack-plugin插件

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]', //新版本无该属性,用filename代替
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

4、 npm run build命令打包报错如下:

vue-cli2添加compression-webpack-plugin压缩代码_第1张图片

原因:项目中webpack版本与compression-webpack-plugin依赖的webpack版本不匹配,且最新版本中无asset属性

Requirements:This module requires a minimum of Node v6.9.0 and Webpack v4.0.0 (此模块最低需要 Node v6.9.0和Webpack v4.0.0)

解决方案:

1. 卸载已经安装的compression-webpack-plugin

npm uninstall --save-dev compression-webpack-plugin

2. 重新安装1.1.12版本

 npm install --save-dev [email protected]

线上使用需后台同步配置
具体可以参考:https://www.cnblogs.com/donghuang/p/10045688.html
官方文档:https://github.com/webpack-contrib/compression-webpack-plugin

你可能感兴趣的:(webpack)