Files
Hugo/content/blog/svelte-first-look.md
T
fukunee 1fb7959071 Standardize poet attributions and reformat blog template
Convert all poet attribution lines to use an em dash, English
name format, and consistent spacing. Re-indent the blog single
page template for readability and adjust the typewriter element
layout.
2026-05-14 02:29:10 +08:00

50 lines
1.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "Svelte 初体验:不一样的思路"
date: 2026-05-10T09:30:00+08:00
draft: false
poet: |
Do not go gentle into that good night.
Rage, rage against the dying of the light.
— Dylan Thomas, UK, 1914–1953
description: "试用了 Svelte 5 的 runes 语法和 SvelteKit 框架。没有虚拟 DOM,编译时直接把组件转成 DOM 操作代码,打包体积小得惊人。"
tags:
- Svelte
- 前端
- JavaScript
---
用惯了 React 和 Vue,第一次接触 Svelte 的时候确实有种新鲜感。最直观的感受:**代码量少了很多**。
## Runes 语法
Svelte 5 引入了 runes 语法,让响应式声明更显式:
- **`$state`** — 声明响应式变量,替代了之前靠赋值触发响应式的隐式规则。
- **`$derived`** — 衍生值,类似 Vue 的 computed。
- **`$effect`** — 副作用,自动追踪依赖并在变化时执行。
```svelte
<script>
let count = $state(0);
let doubled = $derived(count * 2);
$effect(() => {
console.log(`count is now ${count}`);
});
</script>
```
逻辑清晰,没有 `useEffect` 的依赖数组心智负担。
## 编译时魔法
Svelte 的核心理念:没有虚拟 DOM,编译器在构建时直接把组件转成高效的 DOM 操作代码。打包体积小得惊人,一个简单的组件可能只有几百字节。对移动端场景尤其友好。
## SvelteKit
SvelteKit 是 Svelte 的全栈框架,文件路由设计简洁。约定优于配置——新建一个 `src/routes/about/+page.svelte`,就自动有了 `/about` 路由。内置 SSR、SSG、CSR 多种渲染模式,服务器端数据加载用 `load` 函数,类型安全做得不错。
## 总结
Svelte 适合想要减少样板代码、追求小打包体积的项目。React 和 Vue 的生态更成熟,但 Svelte 的思路值得关注。下一步打算用 SvelteKit 重写个人博客试试看。