小编典典

为什么我不能导入 .svelte 组件?

javascript

我最近有这个问题。我无法将 search.svelte 文件导入 index.svelte。以下是详细信息。

index.svelte

<script lang="ts">
    import Search from "src/routes/search.svelte";
</script>

<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

<Search/>

搜索.svelte

只是一个用于演示目的的输入框。

<input type="text">

这是错误

Error: Cannot find module 'src/routes/search.svelte' imported from 'D:/VScode/Repos/Svelte-Endpoints/src/routes/index.svelte'
    at viteResolve (file:///D:/VScode/Repos/Svelte-Endpoints/node_modules/vite/dist/node/chunks/dep-1513d487.js:50354:25)
    at nodeImport (file:///D:/VScode/Repos/Svelte-Endpoints/node_modules/vite/dist/node/chunks/dep-1513d487.js:50389:15)
    at ssrImport (file:///D:/VScode/Repos/Svelte-Endpoints/node_modules/vite/dist/node/chunks/dep-1513d487.js:50284:20)
    at eval (/src/routes/index.svelte:7:37)
    at async instantiateModule (file:///D:/VScode/Repos/Svelte-Endpoints/node_modules/vite/dist/node/chunks/dep-1513d487.js:50330:9)

我无法理解这是怎么发生的。它是一个 .svelte 文件,而不是某个外部库或某些可能导致错误的东西。


阅读 94

收藏
2022-07-26

共1个答案

小编典典

这是因为相对路径与绝对路径。如果您的文件结构如下:

/src/routes/index.svelte
/src/routes/Search.svelte

你会做的

import Search from './Search.svelte';

也就是说,您不应该有这样的文件结构,因为下面的所有文件src/routes都是一条路径,这意味着您将同时拥有http://my-site/http://my-site/Search

最好将组件放在一个不同的文件夹中,例如src/lib/components,如果你这样做,SvelteKit 默认配置了别名,这样你就可以做到

import Search from '$lib/components/Search.svelte';
2022-07-26