skip to Main Content

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


  1. 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:

    // Assuming dynamicComponentPath is a variable containing the path to your component
    const dynamicComponentPath = 'path/to/YourComponent.vue';
    
    // Using dynamic import to load the component asynchronously
    const dynamicComponent = () => import(`@/${dynamicComponentPath}`);
    
    export default {
      components: {
        DynamicComponent: dynamicComponent,
      },
      // Your component logic here
    };
    

    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.

    Make sure your build tool (like webpack) supports dynamic imports and
    code splitting. If you’re using the Vue CLI, it’s likely configured to
    work out of the box.

    Login or Signup to reply.
  2. 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:

    const modules = import.glob('./components/*.vue');
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search