? ? ? 先說(shuō)作者自己按需引入elementui的好處,全局引入是超過(guò)1M的,按需引入后不到400K,作者按需引入用到的組件有分頁(yè),日期選擇器,tree選擇器,input.
第一步:
? ? ?項(xiàng)目目錄執(zhí)行 npm install babel-plugin-component –D
第二步:修改.babelrc
這是Vue腳手架項(xiàng)目按需引入elementui核心的地方,因?yàn)榇蟛糠中率植粫?huì)babel配置.
如果直接復(fù)制粘貼官網(wǎng)提供的配置文件肯定會(huì)報(bào)錯(cuò),因?yàn)槟惆涯_手架默認(rèn)的配置給覆蓋掉了,正確的做法是做整合,babelrc應(yīng)該修改為:
{
? "presets": [
? ? ["env", {
? ? ? "modules": false,
? ? ? "targets": {
? ? ? ? "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
? ? ? }
? ? }],
? ? ["es2015", { "modules": false }],
? ? "stage-2",
? ],
? "plugins": [
? ? ? "transform-vue-jsx",
? ? ? "transform-runtime",
? ? ? [
? ? ? ? ? ? "component",
? ? ? ? ? ? {
? ? ? ? ? ? ? "libraryName": "element-ui",
? ? ? ? ? ? ? "styleLibraryName": "theme-chalk"
? ? ? ? ? ? }
? ? ? ]
? ]
}

第三步:按需引入組件
比如要按需引入button,則為
? import Vue from 'vue'?
? import App from './App'?
? import router from './router'
? import 'element-ui/lib/theme-chalk/index.css'?
import { Button } from 'element-ui'
? ?Vue.use(Button)
? 貼張作者個(gè)人引入的例子:

第四步.錯(cuò)誤處理
如果報(bào)錯(cuò)Module build failed: Error: Couldn't find preset "es2015" relative to directory
?則執(zhí)行npm install babel-preset-es2015 --save-dev
報(bào)錯(cuò)These dependencies were not found:deepmerge,resize-observer-polyfill ,throttle-debounce/debounce
則npm install --save deepmerge resize-observer-polyfill throttle-debounce/debounce
在線(xiàn)例子:這里有個(gè)作者寫(xiě)的vue-cli按需引入elementui的例子可以參考
GitHub - bill-mark/elementui-demand: vue 2.X和elementui 2.X搭配使用時(shí),按需引入.