Svelte簡單入門指南:從項目搭建到組件交互與路由配置

本文將詳細介紹如何使用 Vite 搭建一個 Svelte + TypeScript 項目,並涵蓋組件交互(父子組件、組件間的數據傳遞和事件傳遞)、Store 的多種使用方式以及路由配置等內容。

什麼是 Svelte?

Svelte 是一種現代的前端框架,與傳統的框架(如 React 和 Vue)不同,Svelte 在構建時將組件編譯為高效的原生 JavaScript 代碼,而不是在運行時解釋。這樣做的好處是減少了框架的開銷,提升了性能,並簡化了代碼結構。

Svelte 可以做什麼?

Svelte 可以用於構建現代的、響應式的前端應用程序。它支持組件化開發、狀態管理、路由等現代前端開發所需的功能。以下是一些常見的應用場景:

  • 單頁面應用(SPA)
  • 複雜的表單和數據處理
  • 實時數據更新的儀表盤
  • 交互性強的用戶界面

Svelte 的優勢

  1. 高性能:由於 Svelte 在構建時將代碼編譯為原生 JavaScript,減少了運行時的開銷,提升了性能。
  2. 簡潔的語法:Svelte 的語法簡潔易懂,減少了樣板代碼,使開發更加高效。
  3. 無虛擬 DOM:Svelte 直接操作 DOM,而不是通過虛擬 DOM,這使得更新更加高效。
  4. 輕量級:生成的代碼體積較小,載入速度更快。

Svelte 與 Vue、React 的對比

編譯時 vs 運行時

  • Svelte:在構建時將代碼編譯為高效的原生 JavaScript。
  • React 和 Vue:在運行時解釋代碼,通過虛擬 DOM 進行更新。

語法和開發體驗

  • Svelte:語法簡潔,減少了樣板代碼,易於上手。
  • React:使用 JSX 語法,靈活但相對複雜。
  • Vue:使用模板語法,介於 Svelte 和 React 之間,易於理解。

性能

  • Svelte:由於編譯時優化,性能通常優於 React 和 Vue。
  • React 和 Vue:通過虛擬 DOM 提供較好的性能,但在極端情況下可能不如 Svelte。

初始化項目

首先,使用 Vite 創建一個新的 Svelte 項目並初始化:

Terminal window
1
npm create vite@latest svelte-ts-app -- --template svelte-ts
2
cd svelte-ts-app
3
npm install

項目結構

項目結構如下:

1
svelte-ts-app/
2
├── node_modules/
3
├── public/
4
│ └── favicon.ico
5
├── src/
6
│ ├── assets/
7
│ ├── components/
8
│ │ ├── ChildComponent.svelte
9
│ │ ├── ParentComponent.svelte
10
│ │ └── SiblingComponent.svelte
11
│ ├── routes/
12
│ │ ├── Home.svelte
13
│ │ └── About.svelte
14
│ ├── stores/
15
│ │ └── counter.ts
16
│ ├── App.svelte
17
│ ├── main.ts
18
│ └── index.css
19
├── .gitignore
20
├── index.html
21
├── package.json
22
├── tsconfig.json
23
├── vite.config.ts
24
└── README.md

配置 TailwindCSS(這一步不是必須)

安裝 TailwindCSS:

Terminal window
1
npm install -D tailwindcss postcss autoprefixer
2
npx tailwindcss init -p

tailwind.config.cjs 中配置 TailwindCSS:

1
/** @type {import('tailwindcss').Config} */
2
module.exports = {
3
content: ["./src/**/*.{html,js,svelte,ts}"],
4
theme: {
5
extend: {},
6
},
7
plugins: [],
8
};

src 目錄下創建一個 index.css 文件,並添加以下內容:

1
@tailwind base;
2
@tailwind components;
3
@tailwind utilities;

main.ts 中引入這個 CSS 文件:

1
import "./index.css";
2
import App from "./App.svelte";
3
4
const app = new App({
5
target: document.body,
6
});
7
8
export default app;

創建組件

ChildComponent.svelte

1
<script lang="ts">
2
import { createEventDispatcher } from "svelte";
3
4
export let message: string;
5
const dispatch = createEventDispatcher();
6
7
function handleClick() {
8
dispatch("notify", { text: "Hello from ChildComponent!" });
9
}
10
</script>
11
12
<div class="p-4 bg-blue-100 rounded">
13
<p>{message}</p>
14
<button
15
on:click={handleClick}
16
class="mt-2 bg-blue-500 text-white px-4 py-2 rounded">Notify Parent</button
17
>
18
</div>

ParentComponent.svelte

1
<script lang="ts">
2
import ChildComponent from "./ChildComponent.svelte";
3
import SiblingComponent from "./SiblingComponent.svelte";
4
5
let parentMessage = "Message from ParentComponent";
6
let childMessage = "";
7
8
function handleNotify(event) {
9
childMessage = event.detail.text;
10
}
11
</script>
12
13
<div class="p-4 bg-green-100 rounded">
14
<p>{parentMessage}</p>
15
<ChildComponent
16
message="Message from ParentComponent to ChildComponent"
17
on:notify={handleNotify}
18
/>
19
<SiblingComponent message={childMessage} />
20
</div>

SiblingComponent.svelte

1
<script lang="ts">
2
export let message: string;
3
</script>
4
5
<div class="p-4 bg-yellow-100 rounded">
6
<p>{message}</p>
7
</div>

使用 Store

在 Svelte 中,Store 是一種用於管理應用狀態的機制,類似於 Vuex(Vue)和 Redux(React)。Svelte 提供了 writablereadablederived 等多種類型的 Store 來滿足不同的需求。

stores/counter.ts

1
import { writable } from "svelte/store";
2
3
export const counter = writable(0);

在組件中使用 Store

1
<script lang="ts">
2
import { counter } from "../stores/counter";
3
</script>
4
5
<div class="p-4 bg-red-100 rounded">
6
<button
7
on:click={() => ($counter += 1)}
8
class="bg-red-500 text-white px-4 py-2 rounded">Increment</button
9
>
10
<p>Counter: {$counter}</p>
11
</div>

路由使用

安裝 SvelteKit 路由

Terminal window
1
npm install @sveltejs/kit

配置路由

src/routes 目錄下創建路由組件:

Home.svelte

1
<script lang="ts">
2
import ParentComponent from "../components/ParentComponent.svelte";
3
</script>
4
5
<div class="p-4">
6
<h1 class="text-2xl">Home</h1>
7
<ParentComponent />
8
</div>

About.svelte

1
<script lang="ts">
2
import { counter } from "../stores/counter";
3
</script>
4
5
<div class="p-4">
6
<h1 class="text-2xl">About</h1>
7
<p>Counter: {$counter}</p>
8
</div>

配置路由

src/App.svelte 中配置路由:

1
<script lang="ts">
2
import { Router, Route } from "@sveltejs/kit";
3
import Home from "./routes/Home.svelte";
4
import About from "./routes/About.svelte";
5
</script>
6
7
<Router>
8
<Route path="/" component={Home} />
9
<Route path="/about" component={About} />
10
</Router>

運行項目

確保你已經安裝了所有依賴,並運行項目:

Terminal window
1
npm run dev

總結

  • 組件交互:展示了父子組件之間的消息傳遞和事件傳遞,以及兄弟組件之間的數據傳遞。
  • Store 的使用:展示了如何使用 Svelte 的 writable store 來管理全局狀態。
  • 路由使用:展示了如何使用 SvelteKit 路由來配置和使用路由。