在使用vue cli3脚手架时,需要按需导入element-ui 组件,步骤如下:

1. 安装element-ui

npm i element-ui -S

 2. 按需导入需要安装,babel-plugin-component

npm install babel-plugin-component -D

 3.官网提供的是,将 .babelrc 修改为:

{
  "presets": [["es2015", { "modules": false }]],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

 注意:项目中没有.babelrc文件,无需新建.babelrc文件,直接可以在babel.config.js中配置即可,如下:

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

 这里需要注意:

需要安装最新的babel编译插件“@babel/preset-env”,检查一下自己项目插件版本,如果不是最新版,可执行以下命令安装
npm install @babel/preset-env -D

 4.在main.js中导入你需要的部分组件,如Button

import Vue from 'vue';
import { Button } from 'element-ui';
import App from './App.vue';

Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
/* 或写为
 * Vue.use(Button)
 * Vue.use(Select)
 */

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

 5. 在App.vue中,加入以下代码

<template>
  <div id="app">
    <el-button>默认按钮</el-button>
    <el-button type="primary">主要按钮</el-button>
    <el-button type="success">成功按钮</el-button>
    <el-button type="info">信息按钮</el-button>
    <el-button type="warning">警告按钮</el-button>
    <el-button type="danger">危险按钮</el-button>
  </div>
</template>

 如果在浏览器中运行,出现如下样式,说明按需导入配置成功: