• Vue 打包优化之 externals 抽离公共的第三方库


    使用 @vue/cli 脚手架构建的 Vue 全家桶项目,默认配置下,打包后会把 vuevue-routeraxiosvuexelement-uiecharts 等公共库打包在一起,导致基础 chunkvendor 包体积特别大,有时一个文件能达到 3-5MB,这会大大影响首次加载速度。因此需要抽离第三方公共库,配合使用 CDN 加速。

    Vue Externals

    一、前言

    项目依赖:

    {
      "name": "vue-web",
      "version": "1.0.0",
      "private": true,
      "scripts": {
        "start": "vue-cli-service serve --mode local",
        "dev": "vue-cli-service serve --mode dev",
        "test": "vue-cli-service build --mode test",
        "serve": "vue-cli-service serve ",
        "s": "nodemon --watch vue.config.js --exec \"npm start\"",
        "build": "vue-cli-service build",
        "build:az": "vue-cli-service build --report",
        "git": "tive git -c tive.git.config.js",
        "lint": "vue-cli-service lint"
      },
      "dependencies": {
        "axios": "^0.18.1",
        "d3": "^6.7.0",
        "dagre-d3": "^0.6.4",
        "echarts": "^5.3.3",
        "element-ui": "^2.15.9",
        "v-clipboard": "^2.2.3",
        "vue": "^2.7.10",
        "vue-router": "^3.6.5",
        "vuex": "^3.6.2"
      },
      "devDependencies": {
        "@vue/cli-plugin-babel": "^3.12.1",
        "@vue/cli-plugin-eslint": "^3.12.1",
        "@vue/cli-service": "^3.12.1",
        "compression-webpack-plugin": "^3.0.0",
        "html-webpack-externals-plugin": "^3.8.0",
        "less": "^3.13.1",
        "less-loader": "^4.1.0",
        "msw": "^0.47.3",
        "msw-tools": "latest",
        "uglifyjs-webpack-plugin": "^2.2.0",
        "vue-template-compiler": "^2.7.10",
        "webpack-bundle-analyzer": "^4.7.0"
      },
      "eslintConfig": {
        "root": true,
        "env": {
          "node": true
        },
        "extends": [
          "plugin:vue/essential",
          "eslint:recommended"
        ],
        "rules": {},
        "parserOptions": {
          "parser": "babel-eslint"
        }
      },
      "postcss": {
        "plugins": {
          "autoprefixer": {}
        }
      },
      "browserslist": [
        "> 1%",
        "last 2 versions",
        "not dead",
        "not ie 11"
      ],
      "msw": {
        "workerDirectory": "public"
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    案例:项目整体使用了 element-ui,其中后台服务消费监控可视化引入了 echarts,元数据表血缘关系图使用了 d3dagre-d3,这几个库本身体积就不小,打包到一起后体积更大。

    二、优化配置

    1. 安装 html-webpack-externals-plugin
    npm i -D html-webpack-externals-plugin
    
    • 1
    1. 配置 vue.config.js
    const CompressionWebpackPlugin = require('compression-webpack-plugin')
    const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
    const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
    const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin')
    
    const isProduction = process.env.NODE_ENV === 'production'
    
    module.exports = {
      publicPath: '/datalk/',
      assetsDir: 'static',
      lintOnSave: false,
      productionSourceMap: false,
      devServer: {
        headers: {
          'Access-Control-Allow-Origin': '*',
        },
        host: '0.0.0.0',
        port: 1024,
        disableHostCheck: true,
        proxy: {
          '/api': {
            target: 'https://tiven.cn/api',
            changeOrigin: true,
            ws: true,
            pathRewrite: {
              '^/api': '',
            },
          },
        },
      },
      configureWebpack: (config) => {
        if (isProduction) {
          config.performance = {
            hints: false,
          }
          config.plugins.push(
            new CompressionWebpackPlugin({
              algorithm: 'gzip',
              test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
              threshold: 10240,
              minRatio: 0.8,
            })
          )
        } else {
          config.devtool = 'source-map'
        }
        
        // HtmlWebpackExternalsPlugin 关键配置 start
        config.plugins.push(
          new HtmlWebpackExternalsPlugin({
            externals: [
              {
                module: 'vue',
                entry: {
                  path: 'dist/vue.min.js',
                  type: 'js',
                },
                global: 'Vue',
              },
              {
                module: 'element-ui',
                entry: ['lib/index.js', 'lib/theme-chalk/index.css'],
                supplements: ['lib/theme-chalk/fonts/'],
                global: 'ELEMENT',
              },
              {
                module: 'axios',
                entry: {
                  path: 'dist/axios.min.js',
                },
                global: 'axios',
              },
              {
                module: 'echarts',
                entry: {
                  path: 'dist/echarts.min.js',
                  attributes: {
                    async: '',
                    // defer: '',
                  },
                },
                global: 'echarts',
                // append: true,
              },
              {
                module: 'd3',
                entry: {
                  path: 'dist/d3.min.js',
                  attributes: {
                    async: '',
                  },
                },
                global: 'd3',
              },
              {
                module: 'dagre-d3',
                entry: {
                  path: 'dist/dagre-d3.min.js',
                  attributes: {
                    async: '',
                  },
                },
                global: 'dagreD3',
              },
            ],
            // hash: true, // 设置后会在引用脚本时加上 hash,如下所示:
            // 
            // outputPath: 'static/lib', // 输出目录,默认为 vendor
            // publicPath: '/assets/', // 公共路径,默认为 /
          })
        )
        // HtmlWebpackExternalsPlugin 关键配置 end
        
        // 生成打包报告
        if (process.env.npm_lifecycle_event === 'build:az') {
          config.plugins.push(new BundleAnalyzerPlugin())
        }
      },
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119

    三、配置说明