因此,当我尝试使用
$lib
或 src/lib
导入一些 .js 或 .txt 时,它工作得很好,但是当尝试导入 .svelte
别名中的组件时,它会在服务器上返回此错误,并且页面上有一个[500] Internal Error
4:52:38 PM [vite] page reload src/routes/Inner.svelte
Error: <UserDiv> is not a valid SSR component. You may need to review your build config to ensure that dependencies are compiled, rather than imported as pre-compiled modules. Otherwise you may need to fix a <UserDiv>.
at Module.validate_component (E:/body/vsc/svelte-learn/node_modules/svelte/src/runtime/internal/ssr.js:142:9)
at eval (E:/body/vsc/svelte-learn/src/routes/+page.svelte:14:35)
at Module.each (E:/body/vsc/svelte-learn/node_modules/svelte/src/runtime/internal/ssr.js:128:10)
at eval (E:/body/vsc/svelte-learn/src/routes/+page.svelte:13:39)
at Object.$$render (E:/body/vsc/svelte-learn/node_modules/svelte/src/runtime/internal/ssr.js:174:16)
at Object.default (E:/body/vsc/svelte-learn/.svelte-kit/generated/root.svelte:74:138)
at eval (E:/body/vsc/svelte-learn/node_modules/@sveltejs/kit/src/runtime/components/layout.svelte:8:41)
at Object.$$render (E:/body/vsc/svelte-learn/node_modules/svelte/src/runtime/internal/ssr.js:174:16)
at eval (E:/body/vsc/svelte-learn/.svelte-kit/generated/root.svelte:63:129)
at $$render (E:/body/vsc/svelte-learn/node_modules/svelte/src/runtime/internal/ssr.js:174:16)
但是当我使用与 +page.svelte 位于同一目录中的组件时它可以工作,这背后的原因是什么?!可以修复吗?!
这是导入代码
+page.svelte
<script>
import {data} from "$lib/testdata.js" //works fine
import {UserDiv} from "$lib/components/UserDiv.svelte" //doesn't work
</script>
<div>
{#each data.users as user}
<UserDiv {user} />
{/each}
</div>
这是组件
src/lib/components/UserDiv.svelte
<script>
export let user;
</script>
<div>
<span>id [{user.id}] belongs to {user.name} who's age {user.age}</span>
</div>
import { UserDiv } from ...
是错误的,因为它是命名导入。组件从 Svelte 文件导出为default导出。
因此,如果没有其他问题(-尽管错误听起来不像导入问题-),那么应该是:
import UserDiv from "$lib/components/UserDiv.svelte";
对。 您应该像这样导入组件:
import UserDiv from "$lib/components/UserDiv.svelte";
请尝试一下并告诉我是否有效。 谢谢