vue生产环境打包优化

281 阅读1分钟
  1. productionSourceMap=false使打包时不生成相应的.map文件
  2. 开启gzip,对应服务器部署相关Nginx配置为
http {
    gzip  on;
    gzip_min_length     1k;
    gzip_buffers        4 8k;
    gzip_http_version   1.0;
    gzip_comp_level     8;
    gzip_proxied        any;
    gzip_types          application/javascript text/css image/gif;
    gzip_vary           on;
    gzip_disable        "MSIE [1-6]\.";
 
    #以下的配置省略...
  1. 部分ui组件库,工具包可使用cdn。在index.html引入cdn路径,或者下载下来放在 /static/ 目录下引入也行

完整配置参考:

const CompressionPlugin = require("compression-webpack-plugin");
const path = require('path');
const isProd = process.env.NODE_ENV === 'production';
const  UglifyJsPlugin = require("uglifyjs-webpack-plugin");
module.exports = {
  publicPath: '',
  productionSourceMap: false,
  configureWebpack: config => {
    const baseConfig = {
      resolve: {
        alias: {
          '@': path.resolve(__dirname, 'src')
        }
      }
    }
    if (isProd) {
      config.mode = 'production';
      config.performance = {
        maxEntrypointSize: 2000000,
        maxAssetSize: 2000000,
        hints: 'warning',
      }
      return {
        ...baseConfig,
        plugins: [
          new CompressionPlugin({
            algorithm: 'gzip',
            test: /\.js$|\.html$|\.css/,
            threshold: 10240,
            minRatio: 0.8,
            deleteOriginalAssets: false
          }),
          new UglifyJsPlugin({
            uglifyOptions: {
              output: {
                comments: false, // 去掉注释
              },
              warnings: false,
              compress: {
                drop_console: true,
                drop_debugger: false,
                pure_funcs: ['console.log'] //移除console
              }
            }

          })
        ],
        externals: {
          'echarts': 'echarts', // 配置使用CDN
          'axios': 'axios',
          "maplibre-gl": "maplibregl",
          "moment":"moment",
          "XLSX":"xlsx",
          "_":"lodash",
        }
      }
    } else {
      return {
        ...baseConfig,
        externals: {
          'echarts': 'echarts', // 配置使用CDN
          'axios': 'axios',
          "maplibre-gl": "maplibregl",
          "moment":"moment",
          "XLSX":"xlsx",
          "_":"lodash",
        }
      }
    }
  },
  lintOnSave: false,
  css: {
    loaderOptions: {
      less: {
        lessOptions: {
          modifyVars: {
            'primary-color': '#31aca5',
            'link-color': '#1DA57A',
            'border-radius-base': '2px',
          },
          javascriptEnabled: true,
        },
      },
    },
  },
  devServer: {
    host: 'localhost',
    port: 5050,
    proxy: {
      '/ra': {
        target: 'http://192.168.1.150:8080',
        changeOrigin: true
      },
      '/api': {
        target: 'http://192.168.1.150:8080',
        changeOrigin: true
      }
    }
  },
}