Vue 3 use dynamic component with dynamic imports Vue 3 use dynamic component with dynamic imports vue.js vue.js

Vue 3 use dynamic component with dynamic imports


I already faced the same situation in my template when I tried to make a demo of my icons which are more than 1k icon components so I used something like this :

import {defineAsyncComponent,defineComponent} from "vue";const requireContext = require.context(    "@/components", //path to components folder which are resolved automatically    true,    /\.vue$/i,    "sync");let componentNames= requireContext    .keys()    .map((file) => file.replace(/(^.\/)|(\.vue$)/g, ""));let components= {};componentNames.forEach((component) => { //component represents the component name    components[component] = defineAsyncComponent(() => //import each component dynamically        import("@/components/components/" + component + ".vue")    );});export default defineComponent({    name: "App",    data() {        return {            componentNames,// you need this if you want to loop through the component names in template                 };    },    components,//ES6 shorthand of components:components or components:{...components }});

learn more about require.context