Svelte 是由 Rich Harris 于 2016 年创建的前端框架,采用 "编译时" 策略——在构建时将代码编译为原生 JavaScript,而不是在浏览器中运行时进行 DOM 操作。Svelte 的名字来源于 "svelte"(苗条的),寓意其轻量高效。
Svelte 的核心定位是 编译时前端框架。它提供了:
Rich Harris 在 2016 年创建了 Svelte,最初作为 Ractive.js 的进化版本。Svelte 的核心思想是:框架应该在构建时工作,而不是在运行时。
// App.svelte
<script>
// 响应式声明
let count = 0;
// 响应式语句
$: doubled = count * 2;
$: if (count > 10) {
console.log("计数超过 10");
}
function increment() {
count += 1;
}
function decrement() {
count -= 1;
}
</script>
<!-- 模板 -->
<main>
<h1>计数: {count}</h1>
<h2>两倍: {doubled}</h2>
<button on:click={increment}>+1</button>
<button on:click={decrement}>-1</button>
{#if count > 5}
<p>计数已超过 5!</p>
{/if}
{#each items as item, i}
<li>{i}: {item.name}</li>
{/each}
<!-- 双向绑定 -->
<input bind:value={name} placeholder="输入姓名" />
<p>你好, {name}!</p>
</main>
<style>
main {
font-family: sans-serif;
}
h1 {
color: #ff3e00;
}
</style>
// Svelte 5 Runes 新语法
<script>
// runes 语法
let count = $state(0);
let name = $state("");
let items = $state([]);
// 计算属性
let doubled = $derived(count * 2);
// 副作用
$effect(() => {
console.log(`计数变为: ${count}`);
});
// 事件处理
function increment() {
count += 1;
}
// Props
let { title = "默认标题" } = $props();
</script>
<h1>{title}</h1>
<p>计数: {count} (两倍: {doubled})</p>
<button onclick={increment}>+1</button>
// 父组件
<script>
import Child from "./Child.svelte";
let childData = "";
function handleMessage(event) {
childData = event.detail;
}
</script>
<Child
name="Alice"
on:message={handleMessage}
/>
<p>来自子组件: {childData}</p>
// 子组件 Child.svelte
<script>
export let name; // Props
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
function sendMessage() {
dispatch("message", "Hello from child!");
}
</script>
<div>
<p>子组件: {name}</p>
<button on:click={sendMessage}>发送消息</button>
<!-- 插槽 -->
<slot>默认内容</slot>
</div>
<script>
import { fade, fly, slide } from "svelte/transition";
import { bounce } from "svelte/easing";
let visible = true;
let items = ["苹果", "香蕉", "橙子"];
</script>
<button on:click={() => visible = !visible}>切换</button>
{#if visible}
<div transition:fade="{{ duration: 500 }}">
淡入淡出
</div>
<div transition:fly="{{ y: 200, duration: 1000 }}">
飞入
</div>
<div transition:slide>
滑动
</div>
{/if}
<!-- 列表动画 -->
{#each items as item, i (item)}
<div animate:flip="{{ duration: 300 }}">
{item}
<button on:click={() => items = items.filter((_, j) => j !== i)}>删除</button>
</div>
{/each}
// store.js
import { writable, readable, derived } from "svelte/store";
// 可写存储
export const count = writable(0);
// 只读存储
export const time = readable(new Date(), (set) => {
const interval = setInterval(() => {
set(new Date());
}, 1000);
return () => clearInterval(interval);
});
// 派生存储
export const doubled = derived(count, $count => $count * 2);
// 在组件中使用
<script>
import { count, doubled } from "./store.js";
import { onDestroy } from "svelte";
// 订阅存储
const unsubscribe = count.subscribe(value => {
console.log("计数:", value);
});
onDestroy(unsubscribe);
function increment() {
count.update(n => n + 1);
}
// 使用 $ 前缀自动订阅
$: console.log($count, $doubled);
</script>
<p>计数: {$count}</p>
<p>两倍: {$doubled}</p>
<button on:click={increment}>+1</button>
// +page.svelte(页面组件)
<script>
import { page } from "$app/stores";
import { enhance } from "$app/forms";
let data;
let count = 0;
// 服务端数据
export let data;
</script>
<svelte:head>
<title>{data.title}</title>
</svelte:head>
<h1>{data.title}</h1>
<p>访问量: {data.visits}</p>
<button on:click={() => count++}>点击: {count}</button>
<!-- 服务端渲染 -->
<form method="POST" use:enhance>
<input name="name" />
<button type="submit">提交</button>
</form>
// +page.server.js(服务端逻辑)
export async function load({ params, cookies }) {
return {
title: "欢迎来到 SvelteKit",
visits: await getVisits()
};
}
export const actions = {
default: async ({ request }) => {
const data = await request.formData();
const name = data.get("name");
await saveName(name);
return { success: true };
}
};
| 对比项 | Svelte | React | Vue |
|---|---|---|---|
| 方式 | 编译时 | 运行时 | 运行时 |
| 虚拟 DOM | ❌ | ✅ | ✅ |
| 包体积 | 极小 | 大 | 中 |
| 学习曲线 | 平缓 | 中等 | 平缓 |
| 性能 | 极高 | 高 | 高 |
| 生态 | 增长中 | 最大 | 大 |
| 适用场景 | 高性能应用 | 通用 | 通用 |
JavaScript ES6+、HTML、CSS
Svelte 组件、响应式声明、模板语法、事件处理
Props、Store、动画、过渡、组件通信、生命周期
SvelteKit、TypeScript 集成、性能优化、Svelte 5 Runes
Svelte 是前端框架的"革命者"。
它用 编译时策略、无虚拟 DOM、响应式声明 重新定义了前端开发的方式。Svelte 是追求极致性能的理想选择。
"Svelte 让框架在编译时消失,只在运行时留下高性能。" ⚡