1.使用ant-design-vue或者element-ui时,如何每个组件都去import导入组件,大大降低了开发效率,如果全局一次性注册会增加项目体积,那么如何实现既不局部引入,也不全局注册?
2.在element-plus官网看到有说明
3.那么在webpack中也是可以使用的,下载unplugin-auto-import,unplugin-vue-components两款插件
pnpm install -D unplugin-auto-import unplugin-vue-components
4.在vue.config.js中配置
const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { AntDesignVueResolver } = require('unplugin-vue-components/resolvers');
AutoImport({
imports: ['vue', 'vue-router'],
resolvers: [AntDesignVueResolver()],
}),
Components({
resolvers: [AntDesignVueResolver()],
}),
5.在项目中使用
<template>
<div id="app">
<!-- <router-view></router-view> -->
<a-button>按钮</a-button>
<a-divider />
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
6.发现报错:AutoImport is not a function,打印AutoImport发现是个对象,AutoImport.defalut才是函数,更改下vue.config.js配置
AutoImport.defalut({
imports: ['vue', 'vue-router'],
resolvers: [AntDesignVueResolver()],
}),
Components.defalut({
resolvers: [AntDesignVueResolver()],
}),
7.运行项目还是报错
Module build failed (from ./node_modules/.pnpm/unplugin@2.2.0/node_modules/unplugin/dist/webpack/loaders/transform.js): Error [ERR_REQUIRE_ESM]: require() of ES Module
发现插件用的是es语法,而我们用的是commonjs语法,如何解决?降低插件版本
"unplugin-auto-import": "0.16.0",
"unplugin-vue-components": "0.22.0",
8.运行之后发现没报错了,完美解决
9.经过测试,发现在使用a-layout、a-layout-sider组件时,报错:ant-design-vue并没有抛出a-layout-sider,控制台也输出了全部抛出的组件,发现并没有抛出a-lay-sider,包括a-layout-header、a-layout-content、a-layout-footer,去node_modules下查看a-design-vue源码,发现只抛出了a-layout组件,其他四个是通过vue.component全局注册的,所以ant-design-vue不适合用unplugin-auto-import,换成element-ui试下,测试el-menu、el-sub-menu、el-menu-item是否会出现同样的问题呢?
10.经过测试element-ui不会报错,查看源码发现element-ui抛出了所有的组件,比如el-menu、el-menu-item、el-sub-menu,所以想要使用unplugin-auto-import只能使用element-ui。