vue2实现组件库的自动按需引入,unplugin-auto-import,unplugin-vue-components
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.运行之后发现没报错了,完美解决