--- name: svelte-runtime license: Apache-2.0 description: Svelte 5 运行时技能。当用户需要使用 Stores、Context、生命周期钩子(onMount/onDestroy/tick)、命令式组件 API(mount/unmount/render/hydrate)、Hydratable Data、Best Practices 或 Vitest 测试时使用。 --- # Svelte Runtime Reference (Svelte 5) 本技能覆盖 Svelte 5 的运行时 API,包括跨组件状态(Stores/Context)、生命周期、命令式 API、SSR 和测试。 ## When to use this skill 当用户需要跨组件共享状态、处理组件生命周期、使用 `mount`/`render` 等命令式 API、或编写 Vitest 组件测试时使用本技能。 ## Critical: Stores (svelte/store) Store 是一种跨组件共享响应式状态的老方式(Svelte 5 推荐用 `.svelte.js` 中的 `$state` 对象替代)。 ### writable ```js import { writable } from 'svelte/store'; const count = writable(0); count.subscribe(v => console.log(v)); // 订阅 count.set(1); // 设置值 count.update(n => n + 1); // 更新 ``` ### readable(不可从外部设置) ```js import { readable } from 'svelte/store'; const time = readable(new Date(), (set) => { const interval = setInterval(() => set(new Date()), 1000); return () => clearInterval(interval); }); ``` ### derived ```js import { derived } from 'svelte/store'; const doubled = derived(count, $c => $c * 2); const combined = derived([a, b], ([$a, $b]) => $a + $b); ``` ### readonly ```js import { readonly, writable } from 'svelte/store'; const readOnlyStore = readonly(writableStore); ``` ### 在组件中使用 ```svelte ``` > Store 必须在组件顶层声明;不要在变量前加 `$` 前缀(那是 `$count`,不是 `count`)。 **Svelte 5 推荐替代方案**: ```js // state.svelte.js export const userState = $state({ name: '', count: 0 }); // 其他组件直接 import ``` ## Critical: Context (svelte) 跨组件层级传递数据,无需 props 层层透传(prop-drilling): ### setContext / getContext ```svelte // Parent.svelte // Child.svelte ``` ### createContext(推荐,类型安全) ```ts // context.ts import { createContext } from 'svelte'; export const [getUserContext, setUserContext] = createContext(); ``` ```svelte // Parent.svelte // Child.svelte ``` ### 响应式 Context 将 `$state` 对象存入 Context: ```svelte setContext('counter', counterState); // ❌ 不要重新赋值整个对象 // counterState = { count: 0 } // ✅ 直接修改属性 counterState.count = 0; ``` ## Critical: Lifecycle Hooks > **Mental model**: Svelte 5 的生命周期只有两个阶段 —— **创建** 与 **销毁**。中间的"状态更新"由 **effect** 处理,因为响应式的最小单位是 effect,不是组件。所以没有 `beforeUpdate`/`afterUpdate` 钩子。 ### onMount 组件挂载到 DOM 后执行(SSR 时不运行): ```svelte ``` > 返回的函数在组件卸载时调用;如果传入 async 函数则清理函数不会被调用(async 函数总是返回 `Promise`)。需要异步任务 + 清理时,用 IIFE 包裹,外部箭头函数同步返回清理函数。 ### onDestroy 组件卸载前执行(SSR 时也运行): ```svelte ``` ### tick 等待 DOM 更新完成后再继续: ```svelte ``` ### 生命周期与 mount/unmount/hydrate 的配合 | 阶段 | mount() | hydrate() | render() (SSR) | unmount() | |---|---|---|---|---| | 同步:组件 script、state、模板 | ✓ | ✓ | ✓ | — | | 同步:插入 DOM / 输出字符串 | ✓ 替换 target | ✓ 复用 SSR DOM | ✓ 返回 head+body | — | | 微任务:`$effect` / `onMount` 触发 | ✓ | ✓ | ✗ | — | | 同步:清理 effect + onDestroy | — | — | ✓(render 完成后) | ✓ | | 异步:过渡 (outro) | — | — | — | `outro:true` 时等待 | > `mount()` 返回时 effect 和 `onMount` 都还没跑;要立刻让它们跑就 `flushSync()`。`hydrate()` 同理。 > `tick()` 和 `flushSync()` 在服务端是 no-op(没有响应式调度)。 ## Critical: Imperative Component API ### mount(客户端挂载) ```js import { mount } from 'svelte'; import App from './App.svelte'; const app = mount(App, { target: document.querySelector('#app'), props: { name: 'world' } }); ``` ### unmount(卸载) ```js import { mount, unmount } from 'svelte'; unmount(app, { outro: true }); // 播放过渡后卸载 ``` ### render(服务端渲染) ```js import { render } from 'svelte/server'; const { head, body } = await render(App, { props: { data } }); ``` ### hydrate(客户端水合) 复用 SSR HTML 并激活为交互式: ```js import { hydrate } from 'svelte'; const app = hydrate(App, { target: document.querySelector('#app') }); ``` ## Critical: Hydratable Data SSR 时序列化数据,客户端水合时复用(避免重复请求): ```svelte

{user.name}

``` ### CSP 支持 `hydratable()` 会在 `render()` 返回的 `head` 中嵌入一段 inline `