在Vue项目中使用Element UI时,如果你觉得main.js文件因按需引入Element UI组件变得太长,你可以新建一个plugins/element.js文件来管理Element UI的按需引入。
首先,安装babel-plugin-component(用于Element UI的按需引入):
npm install babel-plugin-component -D
然后,在babel.config.js中配置插件:
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
plugins: [
[
'component',
{
'libraryName': 'element-ui',
'styleLibraryName': 'theme-chalk'
}
]
]
};
接下来,在plugins/element.js中引入所需的Element UI组件:
import Vue from 'vue';
import {
Button,
Select,
// ... 更多组件
} from 'element-ui';
Vue.use(Button);
Vue.use(Select);
// ... 更多组件
// 可以添加配置
Button.defaults({
size: 'small'
});
最后,在main.js中引入这个插件:
import Vue from 'vue';
import App from './App.vue';
import './plugins/element.js';
new Vue({
render: h => h(App),
}).$mount('#app');
这样,main.js就不用再写一大堆按需引入的代码,看起来会更简洁。