Skip to main content

svelte-reference

Svelte 5 API 参考技能。当用户需要查阅 svelte/action、svelte/store、svelte/transition、svelte/animate、svelte/easing、svelte/compiler、svelte/events 的具体 API,或需要查看编译器错误/警告代码时使用。

Ir a la instalación

Datos de origen

Repositorio
full-stack-skills/svelte-skills
Última actividad en el origen
11 de septiembre de 2026 a las 13:43
Idioma detectado de SKILL.md
Varios idiomas
Estrellas
3
Forks
2

Opciones de instalación

De forma predeterminada está seleccionado el prompt que primero revisa el origen. Puedes cambiar a un comando directo o descargar una copia local.

Revisa los archivos de origen

Lee SKILL.md y los archivos complementarios que muestra SkillsMP antes de decidir si quieres instalarlo.

Explorador de archivos
16 archivos

Mostrando SKILL.md

SKILL.md
Instrucciones de origen · Vista previa de solo lectura
name
svelte-reference
license
Apache-2.0
description
Svelte 5 API 参考技能。当用户需要查阅 svelte/action、svelte/store、svelte/transition、svelte/animate、svelte/easing、svelte/compiler、svelte/events 的具体 API,或需要查看编译器错误/警告代码时使用。
# Svelte API Reference (Svelte 5) 本技能是 Svelte 官方模块 API 的快速参考,包括 `svelte/store`、`svelte/action`、`svelte/transition`、`svelte/animate`、`svelte/easing`、`svelte/events`、`svelte/compiler` 及常见编译器/运行时错误代码。 ## When to use this skill 当用户需要查阅 Svelte 具体模块的 API 签名、使用 `transition` / `in` / `out` / `animate` 指令、`use:` action、`easing` 函数、错误代码含义,或需要编译器配置时使用本技能。 ## Critical: svelte/store ```js import { writable, readable, derived, readonly, get } from 'svelte/store'; ``` | 函数 | 签名 | 说明 | |------|------|------| | `writable` | `(initial, start?) => { subscribe, set, update }` | 可写 store | | `readable` | `(initial, start) => { subscribe }` | 只读 store(值只能由内部 `start` 设置) | | `derived` | `(stores, fn, initial?) => { subscribe }` | 派生 store | | `readonly` | `(store) => store` | 返回只读版本(无 `set`/`update`) | | `get` | `(store) => value` | 非订阅获取值(同步,创建临时订阅) | ### Store Contract ```ts store = { subscribe: (subscription: (value: any) => void) => (() => void), set?: (value: any) => void } ``` ### When to Use Stores vs Runes - **Prefer runes** (`$state` in `.svelte.js` files) for shared state and logic extraction. - **Use stores** when you have complex async data streams, need manual control over updates, or want RxJS-style operators. ### `writable` Start Function `writable(initial, start)` — the `start` callback is called when the subscriber count goes `0 → 1` (not `1 → 2`). Return a `stop` function that runs when subscribers go `1 → 0`. The `start` callback also receives an `update` function (in addition to `set`) for transform-based updates. ### `derived` Forms ```js // single store const doubled = derived(a, ($a) => $a * 2); // array of stores const sum = derived([a, b], ([$a, $b]) => $a + $b); // async — second arg is `set`, third is `update`, third `derived` arg is initial value const delayed = derived(a, ($a, set) => { setTimeout(() => set($a), 1000); }, 0); // with cleanup — return a function from the callback const tick = derived(frequency, ($frequency, set) => { const id = setInterval(() => set(Date.now()), 1000 / $frequency); return () => clearInterval(id); }, 0); ``` ### `get(store)` Caveat Creates a temporary subscription, reads, then unsubscribes. Avoid in hot paths. ## Critical: svelte/action (use: directive) Actions are functions called when an element is mounted, added with the `use:` directive: ```svelte <script> /** @type {import('svelte/action').Action} */ function myAction(node) { // node: HTMLElement — runs once on mount (client only, not SSR) $effect(() => { // setup return () => { // teardown — runs on unmount }; }); } </script> <div use:myAction>...</div> ``` > [!NOTE] > In Svelte 5.29 and newer, consider using [`{@attach ...}`](@attach) instead — more flexible and composable. ### Action With Parameter The parameter is **not reactive** — the action runs once on mount. Use `$effect` inside to react to parameter changes. ```svelte <script> /** @type {import('svelte/action').Action<HTMLInputElement, number>} */ function debounce(node, delay) { $effect(() => { const handler = () => setTimeout(() => node.dispatchEvent(new Event('done')), delay); node.addEventListener('input', handler); return () => node.removeEventListener('input', handler); }); } </script> <input use:debounce={300} /> ``` ### Legacy `update`/`destroy` Form ```svelte <script> /** @type {import('svelte/action').Action<HTMLDivElement, string>} */ function colorize(node, color) { node.style.color = color; return { update(newColor) { node.style.color = newColor; }, destroy() { node.style.color = ''; } }; } </script> <div use:colorize={'red'}>...</div> ``` Prefer the `$effect` form for new code. ### Typing — `Action<Node, Parameter, Events>` ```svelte <script lang="ts"> import type { Action } from 'svelte/action'; const gestures: Action<HTMLDivElement, undefined, { onswipeleft: (e: CustomEvent) => void; onswiperight: (e: CustomEvent) => void; }> = (node) => { // dispatch: node.dispatchEvent(new CustomEvent('swipeleft')); }; </script> <div use:gestures onswipeleft={next} onswiperight={prev}>...</div> ``` The third type parameter makes `onswipeleft` / `onswiperight` type-check in the template. ## Critical: svelte/transition (transition: directive) ```svelte <script> import { fade, fly, slide, scale, blur, draw, crossfade } from 'svelte/transition'; </script> {#if visible} <div transition:fade={{ duration: 300, delay: 100 }}>fade</div> <div transition:fly={{ y: 20, duration: 300 }}>fly</div> <div transition:slide>slide</div> <div transition:scale={{ start: 0.5, duration: 300 }}>scale</div> <div transition:blur={{ amount: 10 }}>blur</div> {/if} ``` `transition:` is **bidirectional** — reverses on interrupt. ### Built-in Transitions | 函数 | 效果 | 关键参数 | |------|------|----------| | `fade` | 透明度 | `duration` | | `fly` | 位置飞入 | `x`, `y`, `opacity` | | `slide` | 滑动 | `axis: 'x' \| 'y'` | | `scale` | 缩放 | `start`, `opacity` | | `blur` | 模糊 + 透明度 | `amount` | | `draw` | SVG 路径绘制 | `speed` or `duration` | | `crossfade` | 成对淡入淡出 | `duration`, `fallback` | ### Transition Parameters ```ts { delay?: number, // ms before starting (default 0) duration?: number, // ms (default 400) easing?: function, // easing (default linear) css?: (t, u) => string,// web animation CSS (preferred) tick?: (t, u) => void // imperative (use only when CSS cannot) } ``` `t` runs `0 → 1` on intro, `1 → 0` on outro. `u = 1 - t`. Easing is applied to `t` before it reaches `css` / `tick`. **`css` and `tick` are mutually exclusive.** ### Local vs Global ```svelte <!-- local: only animates when this block is created/destroyed --> <div transition:fade>...</div> <!-- global: animates whenever ANY ancestor block toggles --> <div transition:fade|global>...</div> ``` ### Transition Events | Event | Fires | |-------|-------| | `introstart` | before intro animation | | `introend` | after intro animation | | `outrostart` | before outro animation | | `outroend` | after outro animation | ```svelte <div transition:fly={{ y: 200, duration: 2000 }} onintrostart={() => (status = 'intro started')} onoutroend={() => (status = 'outro ended')} >...</div> ``` ### Custom Transition Function ```ts // @noErrors transition = ( node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' } ) => { delay?: number; duration?: number; easing?: (t: number) => number; css?: (t: number, u: number) => string; tick?: (t: number, u: number) => void; } ``` If the function returns a **function** (instead of an object), Svelte calls it in the next microtask — this is what `crossfade` uses to coordinate paired transitions. ## Critical: in: and out: (separate transitions) `in:` and `out:` are **unidirectional** — they do **not** reverse on interrupt. If you toggle a block off mid-intro, the in-flight intro is **abandoned** and the out-transition restarts from `t=0`. ```svelte <script> import { fade, fly } from 'svelte/transition'; let visible = $state(false); </script> {#if visible} <!-- flies in, fades out — NOT a reversible fly/fade --> <div in:fly={{ y: 200 }} out:fade>...</div> {/if} ``` | Directive | When it runs | Reversible on interrupt? | |-----------|--------------|--------------------------| | `transition:` | enter or leave | **yes** (reverses mid-flight) | | `in:` | enter only | **no** (abandoned) | | `out:` | leave only | **no** (always plays forward) | Use `in:` / `out:` when enter and exit animations should be visually different. The third argument to a custom transition function is `{ direction: 'in' | 'out' | 'both' }`. ## Critical: svelte/easing ```js import { cubicIn, cubicOut, cubicInOut, elasticOut, bounceOut } from 'svelte/easing'; ``` | 缓动 | 说明 | |------|------| | `linear` | 匀速 | | `quadIn`/`quadOut`/`quadInOut` | 二次 | | `cubicIn`/`cubicOut`/`cubicInOut` | 三次缓动 | | `quartIn`/`quartOut`/`quartInOut` | 四次 | | `quintIn`/`quintOut`/`quintInOut` | 五次 | | `sineIn`/`sineOut`/`sineInOut` | 正弦 | | `expoIn`/`expoOut`/`expoInOut` | 指数 | | `circIn`/`circOut`/`circInOut` | 圆 | | `elasticIn`/`elasticOut`/`elasticInOut` | 弹性 | | `backIn`/`backOut`/`backInOut` | 回退 | | `bounceIn`/`bounceOut`/`bounceInOut` | 弹跳 | ```svelte <div transition:fly={{ y: 100, easing: cubicOut }}>...</div> ``` ## Critical: animate: (svelte/animate) `animate:` runs when the **index of an existing item changes** inside a keyed `{#each}` block — not on add/remove. It must be on the **immediate child** of a keyed each block. ```svelte <script>
Ver en GitHub
Este SKILL.md es muy grande, por eso SkillsMP muestra aqui solo la primera seccion. Ver en GitHub