版權聲明:本文為博主原創文章,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://yotrolz.com/posts/97624e89/
前言
使用nuxt+element-UI開發的項目,在進行打包的時候打包提示vendor.xxxxx.js文件過大的警告,所以需要進行優化
打包分析
nuxt配置打包分析
說明:
Nuxt.js 使用webpack-bundle-analyzer
分析并可視化構建后的打包文件,你可以基于分析結果來決定如何優化它。
配置:
在nuxt.config.js
文件中進行配置,具體配置如下:
module.exports = {
build: {
analyze: true
// or
analyze: {
analyzerMode: 'static'
}
}
}
使用:
可通過 nuxt build --analyze
或 nuxt build -a
命令來啟用該分析器進行編譯構建
分析結果:
nuxt build --analyze分析結果
優化前
按照上面的配置后我們可以看到分析結果,如下圖:
優化前
可以看的出項目
element-UI
以及項目依賴的vue等js庫都打包到vendor.xxxxx.js文件中了,隨著引用的庫越多,vendor.xxxxx.js文件肯定就是越大。(這里我們主要對element-ui
庫進行優化)
優化后
優化方案
由于項目中并沒有用到element-UI
中的全部組件,所以我們的優化方案就是只引入我們使用的組件及樣式;
優化步驟
本地安裝按需加載插件babel-plugin-component(已安裝的忽略次步驟)
npm install babel-plugin-component -D
配置nuxt.config.js
// nuxt.config.js
build: {
...other
// 按需引入element-ui
babel: {
plugins: [
[ "component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
},
},
修改plugins/element-ui.js
// plugins/element-ui.js
import Vue from 'vue'
import locale from 'element-ui/lib/locale/lang/en'
// 全局引用
// import Element from 'element-ui'
// 按需引用
import { Button, Input } from 'element-ui'
// 自定義主題樣式(這里我們會在這個文件內引入我們所需的組件的樣式)
import '../assets/stylesheets/element-variables.scss'
// Vue.use(Element, { locale })
// 按需使用
Vue.use(Button, { locale })
Vue.use(Input, { locale })
修改element-variables.scss
// element-variables.scss
/* 改變主題色變量 */
$--color-primary: teal;
/* 改變 icon 字體路徑變量,必需 */
$--font-path: '../../node_modules/element-ui/lib/ theme-chalk/fonts';
/* 樣式--全局引入 */
// @import "~element-ui/packages/theme-chalk/src/index";
/* 樣式--按需引入 */
@import "../../node_modules/element-ui/packages/theme-chalk/src/button";
@import "../../node_modules/element-ui/packages/theme-chalk/src/input";
優化結果
優化結果