I would like to import a list of components using vite like this:
defineAsyncComponent(() => import(`${path}.vue`))
But I get a MIME type error.
I would like to import a list of components using vite like this:
defineAsyncComponent(() => import(`${path}.vue`))
But I get a MIME type error.
2
Answers
In Vue.js, you can import a component by interpolating its path using dynamic import statements, especially when you need to load components conditionally or asynchronously. This is commonly done using webpack’s code-splitting feature. Here’s an example of how you can import a Vue component dynamically with an interpolated path:
Assuming you have a variable containing the component’s path, you can use the following approach:
In this example, the import(@/${dynamicComponentPath}) statement uses a template string to interpolate the path dynamically. The @/ is a shorthand for the src directory in your Vue project. Adjust it based on your project’s structure.
Vite cannot import nested dynamic paths:
https://vitejs.dev/guide/features.html#dynamic-import
That’s because Vite is a packer and it needs to resolve paths statically.
If you want a folder path just use
import.glob
:https://vitejs.dev/guide/features.html#glob-import
You can find all files you need with a pattern:
Then when you need component dynamically you search it
modules
by a file path and get an import function to load it dynamically.Note that all components found with
import.glob
arent treeshakable, so they all will be included in the bundle regardless whether you use them in the app or not.