Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

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’.

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.

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>

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>

Edit this page on GitHub

<script>
import { message } from '../lib/message.js';
</script>

<h1>home</h1>
<p>{message}</p>
booting webcontainer