Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

因为 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:

src/routes/a/deeply/nested/route/+page
<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:

src/routes/+page
<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>
1
2
3
4
5
6
<script>
	import { message } from '../lib/message.js';
</script>
 
<h1>home</h1>
<p>{message}</p>