When trying to load a component using defineAsyncComponent
, the component name that should be rendered is retrieved from the backend. I have created a function specifically for loading the component.
const defineAsyncComponentByName = (componentName: string | undefined) => {
if (componentName) {
return defineAsyncComponent(
() => import(`../${componentName}/${componentName}.vue`)
)
}
}
However, during runtime, an error occurs and the component fails to render.
CustomComponent.vue?t=1701850583908:194 Error: Unknown variable dynamic import: ../CustomComponent/CustomComponent.vue
at dynamic-import-helper:7:96
at new Promise (<anonymous>)
at default (dynamic-import-helper:6:12)
at CustomComponent.vue:54:12
at load (runtime-core.esm-bundler.js:2369:62)
at setup (runtime-core.esm-bundler.js:2449:7)
at callWithErrorHandling (runtime-core.esm-bundler.js:158:18)
at setupStatefulComponent (runtime-core.esm-bundler.js:7327:25)
at setupComponent (runtime-core.esm-bundler.js:7288:36)
at mountComponent (runtime-core.esm-bundler.js:5683:7) 'AsyncComponentWrapper' 'async component loader'
I need to solve this issue. As an update, I modified the function as follows.
const defineAsyncComponentByName = (componentName: string | undefined) => {
if (componentName) {
const importString = `../${componentName}/${componentName}.vue`
return defineAsyncComponent(() => import(importString))
}
}
While this change fixed the problem locally, it doesn't work in production. Additionally, Vite displays a warning on the command line.
The above dynamic import cannot be analyzed by Vite.
See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.