vue-cli3中Element-UI按需加载

5,770 阅读1分钟

npm 安装

npm i element-ui -S

引入 Element

完整引入

在 main.js 中写入以下内容:

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'

Vue.use(ElementUI);

new Vue({
  el: '#app',
  render: h => h(App)
})

按需引入

借助 babel-plugin-component,我们可以只引入需要的组件,以达到减小项目体积的目的。

npm install babel-plugin-component -D

然后,在根目录下新建 babel.config.js 文件,写入以下内容:

module.exports = {
  presets: [
    ['@babel/preset-env', { 'modules': false }]
  ],
  'plugins': [
    [
      'component',
      {
        'libraryName': 'element-ui',
        'styleLibraryName': 'theme-chalk'
      }
    ]
  ]
}

在 main.js 中按需引入

import Vue from 'vue'
import { Button, Select, Notification, Message } from 'element-ui'
import App from './App.vue'

Vue.use(Button)
Vue.use(Select)
Vue.prototype.$notify = Notification
Vue.prototype.$message = Message

new Vue({
  el: '#app',
  render: h => h(App)
})