vue-cli3.0打包优化

215 阅读1分钟

配置 gzip 压缩,打出来一个待 gzip 后缀的文件

下包$ npm i compression-webpack-plugin
vue.config.js写入以下代码:

const CompressionWebpackPlugin = require('compression-webpack-plugin');
module.exports = { 
    configureWebpack: config => { 
        if (process.env.NODE_ENV === 'production') { 
            config.plugins.push( 
                ...[ 
                    new CompressionWebpackPlugin({ 
                   filename: '[path].gz[query]',
                   algorithm: 'gzip', test: /\.(js|css|html|svg)$/i,
                   threshold: 2048, minRatio: 0.8 
}) ] ); } } };

webpack-bundle-analyzer 分析包

下包$ npm i webpack-bundle-analyzer -

module.exports = {
  chainWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
  // 启动时动态创建一个 html:http://localhost:8888/report.html
  // config.plugin('webpack-bundleanalyzer').use(require('webpack-bundleanalyzer').BundleAnalyzerPlugin);
  // 生成一个静态 html,report.html
  config.plugin('webpack-report').use(require('webpackbundle-analyzer').BundleAnalyzerPlugin, [
  {
  analyzerMode: 'static'
  }
  ]);
  }
  }
  };

uglifyjs-webpack-plugin 代码打包与压缩

$ npm install uglifyjs-webpack-plugin --save-dev

configureWebpack: config => {
  // 生产环境相关配置
  if (isProduction == "production") {
  // 代码压缩
  config.plugins.push(
  new UglifyJsPlugin({
  uglifyOptions: {
  //生产环境自动删除 console
  warnings: false,
  compress: {
  // warnings: false, // 若打包错误,则注释这行
  drop_debugger: true,
  drop_console: true,
  pure_funcs: ['console.log']
  }
  },
  sourceMap: false,
  parallel: true
  })
  )
  }
  }
  

图片打包与压缩

$ npm install --save-dev image-webpack-loader

{
  test: /\.(png|gif|jpe?g|svg)$/i,
  exclude:[path.resolve(process.cwd(), 'src/assets/css')],
  use: [
  {
  loader: 'url-loader',
  options: {
  limit: 1024,
  name: '[hash:8].[ext]',
  useRelativePath: false,
  outputPath: function(fileName){
  return 'assets/images/'+fileName
  }
  }
  },
  {
  loader:'image-webpack-loader'
  }
  ]
  }