因为 SvelteKit 使用基于目录的路由,所以很容易将模块和组件放置在使用它们的路由旁边。一个好的经验法则是 ‘将代码放在靠近使用位置的地方’。
¥Because SvelteKit uses directory-based routing, it’s easy to place modules and components alongside the routes that use them. A good rule of thumb is ‘put code close to where it’s used’.
有时,代码在多个地方使用。发生这种情况时,有一个地方放置它们很有用,可以通过所有路由访问,而无需在导入前加上 ../../../../。在 SvelteKit 中,该位置是 src/lib 目录。此目录内的任何内容都可以通过 $lib 别名由 src 中的任何模块访问。
¥Sometimes, code is used in multiple places. When this happens, it’s useful to have a place to put them that can be accessed by all routes without needing to prefix imports with ../../../../. In SvelteKit, that place is the src/lib directory. Anything inside this directory can be accessed by any module in src via the $lib alias.
本练习中的两个 +page.svelte 文件都导入了 src/lib/message.js。但如果你导航到 /a/deeply/nested/route,应用就会中断,因为我们的前缀错误。更新它以改用 $lib/message.js:
¥Both +page.svelte files in this exercise import src/lib/message.js. But if you navigate to /a/deeply/nested/route, the app breaks, because we got the prefix wrong. Update it to use $lib/message.js instead:
<script>
import { message } from '$lib/message.js';
</script>
<h1>a deeply nested route</h1>
<p>{message}</p><script lang="ts">
import { message } from '$lib/message.js';
</script>
<h1>a deeply nested route</h1>
<p>{message}</p>对 src/routes/+page.svelte 执行相同操作:
¥Do the same for src/routes/+page.svelte:
<script>
import { message } from '$lib/message.js';
</script>
<h1>home</h1>
<p>{message}</p><script lang="ts">
import { message } from '$lib/message.js';
</script>
<h1>home</h1>
<p>{message}</p><script>
import { message } from '../lib/message.js';</script>
<h1>home</h1>
<p>{message}</p>