Vue dynamic import with variable not working

239 Views Asked by At

I'm trying to load my vue3 components dynamically. I have defined aliases in the vite config file, when not importing dynamically this works fine and without problem. But when I do a dynamic import, I get the following message:

Uncaught (in promise) TypeError: The specifier “@component/FormGroup/Helper” was a bare specifier, but was not remapped to anything. Relative module specifiers must start with “./”, “../” or “/”.

Somehow the alias doesn't seem to be working when doing a dynamic import like this. How an I solve this problem?

./vite.config.js

import vue            from '@vitejs/plugin-vue';
import laravel        from 'laravel-vite-plugin';
import {defineConfig} from 'vite';

const path = require('path');

export default defineConfig({
    plugins: [
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
    resolve: {
        alias: {
            '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'),
            '@bootstrap': path.resolve(__dirname, 'resources/js/components/bootstrap'),
            '@class': path.resolve(__dirname, 'resources/js/class'),
            '@component': path.resolve(__dirname, 'resources/js/components'),
        },
        extensions: ['.tsx', '.ts', '.js', '.vue'],
    }
});

resources/js/components/FormGroup.vue

<script>
/**
 * Get async loader for component
 *
 * @param {string} path
 * @returns {Object}
 */
function getComponent(path){
    return defineAsyncComponent({
        loader: () => import (path /* @vite-ignore */)
    });
}

import {defineAsyncComponent} from 'vue';

export default {
    name: "FormGroup",
    inheritAttrs: false,
    components: {
        Helper: getComponent('@component/FormGroup/Helper'),
        InputField: getComponent('./FormGroup/InputField'),
    },

I tried to do a dynamic import in resources/js/components/FormGroup.vue. Then it does work, but then I need to repeat the same code for like 10 times, so I'd like to automate the dynamic import using a function.

0

There are 0 best solutions below