在使用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>
如果在瀏覽器中運行,出現如下樣式,說明按需導入配置成功: