SuperAPI AI 工具集

svelte-runtime

前端与建站

查看项目

更新于 10-16 05:48

技能介绍

用途:本技能面向 Svelte 5 运行时 API,帮助处理跨组件状态共享、组件生命周期、命令式挂载/渲染、SSR 水合与组件测试。

主要能力:Stores(writable/readable/derived/readonly,$ 前缀订阅);Context(setContext/getContext 与类型安全的 createContext);生命周期钩子 onMount/onDestroy/tick;命令式 API mount/unmount/render/hydrate;Hydratable Data 与 CSP nonce/hash 支持;Vitest 单元与组件测试。

使用方式:Store 需在组件顶层声明,模板中用 $count 订阅;Context 用 createContext 提供类型安全,响应式 Context 应直接改属性而非重新赋值整个对象。onMount 返回清理函数,异步逻辑需用 IIFE 包裹以同步返回清理函数。mount 后 effect 在微任务触发,需立即执行可用 flushSync()。SSR 用 render 返回 head/body,客户端用 hydrate 复用 HTML。测试安装 npm install -D vitest,组件测试用 mount/unmount,状态更新用 flushSync() 强制同步。

适用场景:跨组件状态共享、SSR 与水合、组件测试、CSP 严格模式下的内联脚本放行。

限制:tick() 与 flushSync() 在服务端为 no-op;render 仅用于 SSR;async onMount 的清理函数会被忽略;hydratable 内联脚本受 CSP 限制,需 nonce 或 hash;hydration 随机值会不匹配,需用 hydratable() 包裹。具体版本与平台支持暂未提供。