Ehr*_*man 5 import dynamic-import svelte sveltekit
我想动态导入组件而不导入特定组件。我想使用从商店收到的变量设置组件名称:
<script lang="ts">
// SVELTE
import { onMount } from 'svelte';
// STORE
import { dynamicComponent } from '$stores/dynamicTitle';
$: $dynamicComponent;
console.log($dynamicComponent)
let renderDynamicComponent
onMount(async () => {
const importValue = (await import(`../../lib/components/Home/DynamicComponents/${String($dynamicComponent)}.svelte`)).default;
// const importValue = (await import(`../../lib/components/Home/DynamicComponents/IntroSectionCustom.svelte`)).default;
renderDynamicComponent = importValue
});
<svelte:component this={renderDynamicComponent}/>
Run Code Online (Sandbox Code Playgroud)
但我得到:
Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: http://localhost:3000/src/lib/components/Home/DynamicComponents/Intro-Section-Custom.svelte
Run Code Online (Sandbox Code Playgroud)
我不明白。从错误来看,这似乎是正确的路径......
我认为 Svelte + 捆绑器当前不支持动态生成的路径:
let thing = 'Thing';
Thing = (await import(`./${thing}.svelte`)).default; // this won't work
Thing = (await import(`./Thing.svelte`)).default; // this will work
Run Code Online (Sandbox Code Playgroud)
捆绑器的限制。
github问题:https ://github.com/sveltejs/svelte/issues/6702