nuxt.config,js 配置 Element-ui 懶加載,實現ui框架按需加載,優化 vendors 大小

前言

nuxt 學習之路 - nuxt.config.js 配置篇。通過實現框架懶加載來實現優化項目打包體積大小。(本篇使用 element-ui 爲例,使用插件 babel-plugin-component)。


一、未優化前

// plugins/element-ui.js
import Vue from 'vue'
import { Button, Loading, Notification, Message, MessageBox } from 'element-ui'

import lang from 'element-ui/lib/locale/lang/zh-CN'
import locale from 'element-ui/lib/locale'

locale.use(lang)

Vue.use(Loading.directive)
Vue.prototype.$loading = Loading.service
Vue.prototype.$msgbox = MessageBox
Vue.prototype.$notify = Notification
Vue.prototype.$message = Message

Vue.use(Button)

運行項目時可以發現,雖然我們只引入 element-ui 的幾個組件,但是 vendors.app.js 文件的體積還是很大,如下圖:
在這裏插入圖片描述

二、使用 babel-plugin-component 實現懶加載,優化打包體積

plugins/element-ui.js 文件的內容不變,先安裝插件(npm i babel-plugin-component -D),再配置 nuxt.config.js,

// nuxt.config.js
module.exports = {
	build: {
	    // 爲 JS 和 Vue 文件設定自定義的 babel 配置。
	    babel: {
	      plugins: [
	        [
	          'component', { libraryName: 'element-ui', styleLibraryName: 'theme-chalk' }
	        ]
	      ]
	    }
	}
}

重新 run 下,可以看到此時的 vendors.app.js 由之前的 2.3Mb 變成了現在的 988kb,babel-plugin-component 實現 按需加載,只把我們引用到的組件加載進來,如下圖:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章