svelte

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Svelte

Svelte

Svelte is a component framework that compiles your code to tiny, framework-less vanilla JS. Svelte 5 (2025) introduces "Runes" for explicit reactivity.
Svelte是一个组件框架,可将代码编译为体积小巧、无需框架依赖的原生JS。Svelte 5(2025年)引入了“Runes”以实现显式响应式。

When to Use

适用场景

  • High Performance defaults: Svelte apps are tiny and fast by default.
  • Embedded Apps: Great for widgets/embeds because of small bundle size.
  • Simplicity: HTML, CSS, and JS in one file, with very little boilerplate.
  • 默认高性能:Svelte应用默认体积小巧且运行快速。
  • 嵌入式应用:因打包体积小,非常适合用于小部件/嵌入式场景。
  • 简洁易用:将HTML、CSS和JS整合在单个文件中,几乎无需冗余模板代码。

Quick Start (Runes)

快速入门(Runes)

svelte
<script>
  let count = $state(0);
  let double = $derived(count * 2);

  function increment() {
    count += 1;
  }
</script>

<button onclick={increment}>
  Count: {count} / Double: {double}
</button>
svelte
<script>
  let count = $state(0);
  let double = $derived(count * 2);

  function increment() {
    count += 1;
  }
</script>

<button onclick={increment}>
  Count: {count} / Double: {double}
</button>

Core Concepts

核心概念

Runes

Runes

Svelte 5 reactivity markers.
  • $state
    : Declares reactive state.
  • $derived
    : Declares a value that updates when dependencies change.
  • $effect
    : Runs code when dependencies change (side effects).
  • $props
    : Declares component props.
Svelte 5的响应式标记。
  • $state
    :声明响应式状态。
  • $derived
    :声明一个会随依赖项变化而更新的值。
  • $effect
    :当依赖项变化时执行代码(副作用)。
  • $props
    :声明组件属性。

Snippets

代码片段(Snippets)

Reusable chunks of markup within a component.
svelte
{#snippet figure(src, caption)}
  <figure>
    <img {src} alt={caption} />
    <figcaption>{caption}</figcaption>
  </figure>
{/snippet}

{@render figure(imageSrc, "A nice image")}
组件内可复用的标记块。
svelte
{#snippet figure(src, caption)}
  <figure>
    <img {src} alt={caption} />
    <figcaption>{caption}</figcaption>
  </figure>
{/snippet}

{@render figure(imageSrc, "A nice image")}

Best Practices (2025)

2025年最佳实践

Do:
  • Use Runes: Migrate from
    let
    +
    $
    syntax to
    $state
    and
    $derived
    for explicit reactivity.
  • Use
    onclick
    : Svelte 5 prefers native attributes (
    onclick
    ) over
    on:click
    directives.
  • Use Snippets: Replace
    slots
    with Snippets for better type safety and flexibility.
Don't:
  • Don't rely on auto-reactivity (Legacy): In Svelte 5 settings, opting into Runes disables the "magic" assignment tracking of Svelte 3/4. This is good for predictability.
推荐做法
  • 使用Runes:从
    let
    +
    $
    语法迁移到
    $state
    $derived
    ,实现显式响应式。
  • 使用
    onclick
    :Svelte 5更推荐使用原生属性
    onclick
    而非
    on:click
    指令。
  • 使用代码片段:用Snippets替代slots,以获得更好的类型安全性和灵活性。
不推荐做法
  • 不要依赖自动响应式(旧版特性):在Svelte 5环境中,启用Runes会禁用Svelte 3/4中的“魔法”赋值追踪功能。这有助于提升代码的可预测性。

References

参考资料