1. 程式人生 > 其它 >Vue打包優化

Vue打包優化

一、 Vue專案優化

1. 生成打包報告

1) 視覺化面板(推薦):vue ui
2) 命令列引數:vue-cli-service build --report

2. 修改webpack預設配置(vue.config.js檔案)

const { defineConfig } = require('@vue/cli-service')

module.exports = defineConfig({
  publicPath: './',
  chainWebpack: config => {
    // 是否是production模式
    const isProd = process.env.NODE_ENV === 'production'

    // 1. 根據isProd設定不同的打包入口
    config
      .entry('app')
      .clear()
      .add(`./src/main-${isProd ? 'prod' : 'dev'}.js`)
    
    // 2. production模式,通過externals載入cdn資源,減小打包後的檔案體積
    if (isProd) {
      config.set('externals', {
        axios: 'axios',
        vue: 'Vue',
        vuex: 'Vuex',
        'element-ui': 'ELEMENT',
        'vue-router': 'VueRouter'
      })
    }

    // 3. 定製index.html內容,根據isProd載入script或樣式
    config
      .plugin('html')
      .tap(args => {
        args[0].isProd = isProd
        return args
      })
  }
})

3. 通過CDN優化打包(index.html與main-prod.js檔案)

1) main-prod.js 檔案中 刪除(推薦)或註釋 使用資源的程式碼
2) index.html 頭部中通過 cdn 載入資源
<!DOCTYPE html>
<html lang="">
  <head>
    <!-- 省略此處程式碼 -->

    <!-- 根據isProd判斷是否載入cdn資源 -->
    <% if (htmlWebpackPlugin.options.isProd) { %>
    <link href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.6/theme-chalk/index.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue-router/3.5.3/vue-router.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vuex/4.0.2/vuex.global.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.6/index.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.26.1/axios.min.js"></script>
    <% } %>
  </head>
  <body>
    <!-- 省略此處程式碼 -->
  </body>
</html>

4. 路由懶載入

1) 安裝 @babel/plugin-syntax-dynamic-import 外掛
2) 在 babel.config.js 配置檔案中宣告該外掛
module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ],
  plugins: [
    '@babel/plugin-syntax-dynamic-import'
  ]
}
3) 將路由改為按需載入的形式
const foo = import(/* webpackChunkName: 'ns_foo' */ './components/Foo.vue')
5. Notice

通過 cdn 的方式引入外部資源,在 內網情況下cdn受到攻擊 會失效。