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。