AgentSkillsCN

svelte5-best-practices

Svelte 5 的运行时指令、代码片段、SvelteKit 模式,以及面向 TypeScript 和组件开发的现代最佳实践。适用于编写、审阅或重构 Svelte 5 组件和 SvelteKit 应用程序时使用。当用户提及 Svelte 组件、运行时指令($state、$derived、$effect、$props、$bindable、$inspect)、代码片段({#snippet}、{@render})、事件处理、SvelteKit 数据加载、表单操作、Svelte 4 至 Svelte 5 的迁移、Store 至运行时指令的迁移、Slot 至代码片段的迁移、TypeScript Props 类型标注、泛型组件、SSR 状态隔离、性能优化,或组件测试时,此技能将自动触发。

SKILL.md
--- frontmatter
name: svelte5-best-practices
description: "Svelte 5 runes, snippets, SvelteKit patterns, and modern best practices for TypeScript and component development. Use when writing, reviewing, or refactoring Svelte 5 components and SvelteKit applications. Triggers on: Svelte components, runes ($state, $derived, $effect, $props, $bindable, $inspect), snippets ({#snippet}, {@render}), event handling, SvelteKit data loading, form actions, Svelte 4 to Svelte 5 migration, store to rune migration, slots to snippets migration, TypeScript props typing, generic components, SSR state isolation, performance optimization, or component testing."
license: MIT
metadata:
  author: ejirocodes
  version: "1.0.0"

Svelte 5 Best Practices

Quick Reference

TopicWhen to UseReference
Runes$state, $derived, $effect, $props, $bindable, $inspectrunes.md
SnippetsReplacing slots, {#snippet}, {@render}snippets.md
Eventsonclick handlers, callback props, context APIevents.md
TypeScriptProps typing, generic componentstypescript.md
MigrationSvelte 4 to 5, stores to runesmigration.md
SvelteKitLoad functions, form actions, SSR, page typingsveltekit.md
PerformanceUniversal reactivity, avoiding over-reactivity, streamingperformance.md

Essential Patterns

Reactive State

svelte
<script>
  let count = $state(0); // Reactive state
  let doubled = $derived(count * 2); // Computed value
</script>

Component Props

svelte
<script>
  let { name, count = 0 } = $props();
  let { value = $bindable() } = $props(); // Two-way binding
</script>

Snippets (replacing slots)

svelte
<script>
  let { children, header } = $props();
</script>

{@render header?.()}
{@render children()}

Event Handlers

svelte
<!-- Svelte 5: use onclick, not on:click -->
<button onclick={() => count++}>Click</button>

Callback Props (replacing createEventDispatcher)

svelte
<script>
  let { onclick } = $props();
</script>

<button onclick={() => onclick?.({ data })}>Click</button>

Common Mistakes

  1. Using let without $state - Variables are not reactive without $state()
  2. Using $effect for derived values - Use $derived instead
  3. Using on:click syntax - Use onclick in Svelte 5
  4. Using createEventDispatcher - Use callback props instead
  5. Using <slot> - Use snippets with {@render}
  6. Forgetting $bindable() - Required for bind: to work
  7. Setting module-level state in SSR - Causes cross-request leaks
  8. Sequential awaits in load functions - Use Promise.all for parallel requests