element-ui 按需引入组件

119 阅读1分钟
  1. 安装插件
npm install babel-plugin-component -D

2..babelrc或者babel.config.js中加上

module.exports = {
  presets: [
    // https://github.com/vuejs/vue-cli/tree/master/packages/@vue/babel-preset-app
    "@vue/cli-plugin-babel/preset",
  ],
  env: {
    development: {
      // babel-plugin-dynamic-import-node plugin only does one thing by converting all import() to require().
      // This plugin can significantly increase the speed of hot updates, when you have a large number of pages.
      plugins: ["dynamic-import-node"],
    },
  },
  
  //加上以下部分
  plugins: [
    [
      "component",
      {
        libraryName: "element-ui",
        styleLibraryName: "theme-chalk",
      },
    ],
  ],
};

3.在src下新建文件夹element-ui,新增文件index.js

//element-ui/index.js
import Vue from "vue";
import {
  Pagination,
  Dialog,
  Autocomplete,
  Loading,
  MessageBox,
  Message,
  Notification
}
Vue.use(Pagination);
Vue.use(Dialog);
Vue.use(Autocomplete);

const _Loading = Loading;
const { directive: loadingDirective, service: loadingService } = _Loading;
const _MessageBox = MessageBox;
const { alert, confirm, prompt } = _MessageBox;

Vue.use(loadingDirective);

Vue.prototype.$loading = loadingService
Vue.prototype.$msgbox = _MessageBox;
Vue.prototype.$alert = alert;
Vue.prototype.$confirm = confirm;
Vue.prototype.$prompt = prompt;
Vue.prototype.$notify = Notification;
Vue.prototype.$message = Message;

Vue.prototype.$ELEMENT = { size: "medium" };

4.main.js中引入element-ui/index.js

如果有全局引入则删除全局引入的部分

//将
import Element from 'element-ui'
 Vue.use(Element, {
   size:  'medium' // set element-ui default size
 })
//改为
import "@/element-ui";

打包试试