preface

When using some component libraries such as Ant-Design-Vue, if the whole component library is introduced into the project, but only part of the components are needed, the project will eventually become too large when packaging, resulting in a slow loading speed, so it needs to be loaded on demand. The official solution is also provided

Vue3.0 uses ant-design-Vue to load on demand, which is easy

New solutions

The use here is vue-CLI 5.0 to generate a VUe3.0 + TS project

  • The first thing you need to do isdevDependenciesTo install two plug-ins
npm install -D unplugin-auto-import unplugin-vue-components
Copy the code
  • Then, invue.config.jsTo configure

Document unplugin – auto – import unplugin – vue – components

const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const {
  ElementPlusResolver, // element
  AntDesignVueResolver, // ant-design-vue
} = require('unplugin-vue-components/resolvers')
module.exports = {
  configureWebpack: {
    plugins: [
      // Automatic import method
      AutoImport({
        include: [
          /\.[tj]sx? $/.// .ts, .tsx, .js, .jsx
          /\.vue$/./\.vue\? vue/.// .vue].imports: [
          'vue'.'vue-router',].resolvers: [ElementPlusResolver()],
        dts: 'typings/auto-imports.d.ts'.// Custom generated.d.ts location
      }),
      // Automatically import components
      Components({
        include: [/\.vue$/./\.vue\? vue/].exclude: [/[\\/]node_modules[\\/]/./[\\/]\.git[\\/]/].resolvers: [
          ElementPlusResolver(), 
          AntDesignVueResolver()
        ],
        dts: 'typings/components.d.ts'.// Custom generated.d.ts location})],}},Copy the code
  • configurationtsconfig.jsonSince these two plug-ins automatically generate declaration files, they need to be manually configured to remove errors in the editor
{..."include": [
    "src/**/*.ts"."src/**/*.tsx"."src/**/*.vue"."tests/**/*.ts"."tests/**/*.tsx"."typings/**/*.ts"."typings/**/*.d.ts"]."exclude": ["node_modules"]}Copy the code
  • I used it simultaneously in the projectant-designandelement-plusComponent libraries, which can be configured to be used in a project, introduce components and methods as needed and use them directly without registration, which greatly improves the development experience
<template>
  <a-button type="primary">{{ text }}</a-button>
  <el-button type="primary">{{ text }}</el-button>
</template>

<script setup lang="ts">
const route = useRoute()
const router = useRouter()
const text = ref<string>('button text')
</script>
Copy the code

It is worth mentioning that the authors of these two plug-ins are Anthony Fu, a key member of Vuejs and the author of VueUse.

If you want to use it in vite + Vue3.0 projects you can take a look at the big guy project Vitesse