欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue?打包優(yōu)化之externals抽離公共的第三方庫詳解

 更新時(shí)間:2023年06月13日 11:34:39   作者:天問  
這篇文章主要為大家介紹了Vue?打包優(yōu)化之externals抽離公共的第三方庫詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪<BR>

一、前言

@vue/cli 腳手架構(gòu)建的 Vue 全家桶項(xiàng)目,默認(rèn)配置下,打包后會把 vue、vue-router、axiosvuex、element-ui、echarts 等公共庫打包在一起,導(dǎo)致基礎(chǔ) chunkvendor 包體積特別大,有時(shí)一個文件能達(dá)到 3-5MB,這會大大影響首次加載速度。因此需要抽離第三方公共庫,配合使用 CDN 加速。

Vue Externals

項(xiàng)目依賴

{
  "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"
  }
}

案例:項(xiàng)目整體使用了 element-ui,其中后臺服務(wù)消費(fèi)監(jiān)控可視化引入了 echarts,元數(shù)據(jù)表血緣關(guān)系圖使用了 d3dagre-d3,這幾個庫本身體積就不小,打包到一起后體積更大。

二、優(yōu)化配置

  • 安裝 html-webpack-externals-plugin
npm i -D html-webpack-externals-plugin
  • 配置 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 關(guān)鍵配置 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, // 設(shè)置后會在引用腳本時(shí)加上 hash,如下所示:
        // <script src='/datalk/vendor/vue/dist/vue.min.js?f452a239c2c0156e7b83'></script>
        // outputPath: 'static/lib', // 輸出目錄,默認(rèn)為 vendor
        // publicPath: '/assets/', // 公共路徑,默認(rèn)為 /
      })
    )
    // HtmlWebpackExternalsPlugin 關(guān)鍵配置 end
    // 生成打包報(bào)告
    if (process.env.npm_lifecycle_event === 'build:az') {
      config.plugins.push(new BundleAnalyzerPlugin())
    }
  },
}

三、配置說明

  • module :庫名,也就是 package.json 中的包依賴名。
  • entry :入口,有幾種類型,string | array<string> | object | array<object | string>,可以設(shè)置 CDN 地址,如:https://cdn.tiven.cn/assets/js/vue.min.js ;也可以設(shè)置文件路徑,如:dist/vue.min.js,相對于項(xiàng)目的路徑就是:node_modules/vue/dist/vue.min.js。
  • global :注冊到 window 上的全局變量,注意不能配錯,否則代碼會報(bào)錯。
  • supplements :補(bǔ)充文件,在上邊 element-ui 配置中,因?yàn)?css 文件中依賴了大量的 font 字體文件,所以在打包時(shí)需要把這些依賴文件根據(jù)相對路徑復(fù)制到 dist 對應(yīng)的目錄中。
  • attributes :設(shè)置引用這些抽離出去包的 scriptlink 標(biāo)簽的屬性,defer、async、crossoriginglobal 等等,可以根據(jù)需要進(jìn)行配置。

因?yàn)槭醉撌状武秩静灰蕾?echartsd3、dagre-d3 等第三方庫,所以給 script 標(biāo)簽加上了 async 屬性,腳本相對于頁面的其余部分異步地執(zhí)行(當(dāng)頁面繼續(xù)進(jìn)行解析時(shí),腳本將被執(zhí)行),這樣可以不阻塞頁面渲染,提升首屏加載速度,提高用戶體驗(yàn)。

四、打包對比

使用 webpack-bundle-analyzer 生成打包報(bào)告,優(yōu)化前如圖所示:

Vue BundleAnalyzer Report

優(yōu)化后如圖所示:

Vue BundleAnalyzer Report

公共包被抽離出去,chunk 包總體積從 2.8MB 變成 670KB ,減小了 70% 多,優(yōu)化效果很明顯。

五、打包輸出

打包后 dist 目錄:

dist/
  static/
    css/
    ...
    img/
    ...
    js/
      app.f462a90f.js
      app.f462a90f.js.gz
      chunk-0af562fc.fcb27ef3.js
      chunk-1f6412f4.625202a5.js
      chunk-1f6412f4.625202a5.js.gz
      ...
  vendor/
    axios/
      dist/
        axios.min.js  
        axios.min.js.gz
    d3/
      dist/
        d3.min.js    
        d3.min.js.gz
    dagre-d3/
      dist/
        dagre-d3.min.js    
        dagre-d3.min.js.gz
    echarts/
      dist/
        echarts.min.js    
        echarts.min.js.gz
    element-ui/
      lib/
        theme-chalk/
          fonts/
            element-icons.ttf
            element-icons.woff
          index.css
          index.css.gz
        index.js    
        index.js.gz
    vue/
      dist/
        vue.min.js    
        vue.min.js.gz
  favicon.ico      
  index.html

打包后,會發(fā)現(xiàn)把這些抽離出去的包直接引入到 index.html 中,如下所示:

<body>
  <noscript>
    <strong>
      We're sorry but regeng doesn't work properly without JavaScript enabled. Please enable it to continue.
    </strong>
  </noscript>
  <div id='app'></div>
  <script src='/datalk/vendor/vue/dist/vue.min.js'></script>
  <script src='/datalk/vendor/element-ui/lib/index.js'></script>
  <script src='/datalk/vendor/axios/dist/axios.min.js'></script>
  <script src='/datalk/vendor/echarts/dist/echarts.min.js' async></script>
  <script src='/datalk/vendor/d3/dist/d3.min.js' async></script>
  <script src='/datalk/vendor/dagre-d3/dist/dagre-d3.min.js' async></script>
  <script src='/datalk/static/js/app.f462a90f.js'></script>
</body>

六、踩坑記錄

element-ui 配置 externals 時(shí),可能會遇到這樣的報(bào)錯:Uncaught ReferenceError: ElementUI is not defined at element-ui (external "ElementUI":1:1) ,這說明 element-ui 模塊的 global 參數(shù)配置錯了,在全局 window 上找不到,你可能配置的是 ElementUI、Element、element-ui,這些都是不對的。必須是 global: 'ELEMENT'。

相關(guān)文章

  • vue3.0如何在全局掛載對象和方法

    vue3.0如何在全局掛載對象和方法

    這篇文章主要介紹了vue3.0如何在全局掛載對象和方法,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • 基于VUE實(shí)現(xiàn)簡單的學(xué)生信息管理系統(tǒng)

    基于VUE實(shí)現(xiàn)簡單的學(xué)生信息管理系統(tǒng)

    這篇文章主要介紹了VUE實(shí)現(xiàn)一個簡單的學(xué)生信息管理系統(tǒng),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • vue樹形結(jié)構(gòu)數(shù)據(jù)處理的方法總結(jié)

    vue樹形結(jié)構(gòu)數(shù)據(jù)處理的方法總結(jié)

    在項(xiàng)目開發(fā)的過程中,會經(jīng)常使用樹形結(jié)構(gòu)數(shù)據(jù),前后端交互都會對數(shù)據(jù)進(jìn)行處理,后端返回的數(shù)據(jù)前端有的時(shí)候不能直接使用需要轉(zhuǎn)換,本文小編整理了一些項(xiàng)目中用到的處理方法,需要的朋友可以參考下
    2023-11-11
  • Vue中引用assets中圖片的實(shí)現(xiàn)方式

    Vue中引用assets中圖片的實(shí)現(xiàn)方式

    這篇文章主要介紹了Vue中引用assets中圖片的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • vue3中7種路由守衛(wèi)的使用大全舉例

    vue3中7種路由守衛(wèi)的使用大全舉例

    最近在學(xué)習(xí)vue,感覺路由守衛(wèi)這個地方知識點(diǎn)挺多的,而且很重要,下面這篇文章主要給大家介紹了關(guān)于vue3中7種路由守衛(wèi)的使用大全,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-03-03
  • Vue3使用customRef封裝防抖函數(shù)的方法詳解

    Vue3使用customRef封裝防抖函數(shù)的方法詳解

    防抖函數(shù)的作用是高頻率觸發(fā)的事件,在指定的單位時(shí)間內(nèi),只響應(yīng)最后一次,如果在指定的時(shí)間內(nèi)再次觸發(fā),則重新計(jì)算時(shí)間,本文將給大家詳細(xì)的介紹一下Vue3使用customRef封裝防抖函數(shù)的方法,需要的朋友可以參考下
    2023-09-09
  • vant-list組件觸發(fā)多次onload事件導(dǎo)致數(shù)據(jù)亂序的解決方案

    vant-list組件觸發(fā)多次onload事件導(dǎo)致數(shù)據(jù)亂序的解決方案

    這篇文章主要介紹了vant-list組件觸發(fā)多次onload事件導(dǎo)致數(shù)據(jù)亂序的解決方案
    2023-01-01
  • Vue3.x的版本中build后dist文件中出現(xiàn)legacy的js文件問題

    Vue3.x的版本中build后dist文件中出現(xiàn)legacy的js文件問題

    這篇文章主要介紹了Vue3.x的版本中build后dist文件中出現(xiàn)legacy的js文件問題及解決,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • vue-music 使用better-scroll遇到輪播圖不能自動輪播問題

    vue-music 使用better-scroll遇到輪播圖不能自動輪播問題

    根據(jù)vue-music視頻中slider組建的使用,當(dāng)安裝新版本的better-scroll,輪播組件,不能正常輪播。如何解決這個問題呢,下面小編給大家?guī)砹藇ue-music 使用better-scroll遇到輪播圖不能自動輪播問題,感興趣的朋友一起看看吧
    2018-12-12
  • Vue Class Component類組件用法

    Vue Class Component類組件用法

    這篇文章主要介紹了Vue Class Component類組件用法,組件 (Component) 是 Vue.js 最強(qiáng)大的功能之一,它是html、css、js等的一個聚合體,封裝性和隔離性非常強(qiáng)
    2022-12-12

最新評論