ข้ามไปยังเนื้อหา

The Component Anatomy

Svelte component คือไฟล์ .svelte ที่มีได้ถึงสามส่วน:

<script>
// 1. Logic: state, props, imports, functions.
let name = $state('world');
</script>
<!-- 2. Markup: HTML plus Svelte template syntax. -->
<h1>Hello {name}!</h1>
<input bind:value={name} />
<style>
/* 3. Styles: scoped to THIS component by default. */
h1 { color: #ff3e00; }
</style>
  • block <script> คือ logic ของ component: state (ด้วย runes), component ที่ import เข้ามา และ function โดย block นี้รันหนึ่งครั้งตอน component ถูกสร้าง
  • markup คือ HTML ที่เสริมด้วย template syntax ของ Svelte — {expressions}, block อย่าง {#if} และ binding นี่คือสิ่งที่ render
  • block <style> คือ CSS ที่โดย default จะ apply เฉพาะ component นี้

ไม่มี boilerplate wrapper ไม่มี return ไม่มี render() — ไฟล์ คือ component

flowchart LR
  script["script: state, props, logic"] --> compile["Svelte compiler"]
  markup["markup: HTML + template syntax"] --> compile
  style["style: scoped CSS"] --> compile
  compile --> comp["a component: JS + a stylesheet"]
สามส่วนของไฟล์ .svelte

block <style> ถูก scope อยู่ที่ component — Svelte เพิ่ม class เฉพาะให้ element ของ component แล้ว rewrite selector ของคุณให้ match เฉพาะ element เหล่านั้น เขียน h1 { color: … } แล้ว style นั้นมีผลกับ h1 ของ component นี้ ไม่ใช่ h1 ทุกตัวบนหน้า

<p>This paragraph is styled locally.</p>
<style>
/* Compiles to something like p.svelte-abc123 { ... } — scoped, no leakage. */
p { font-weight: bold; }
</style>

คุณได้ CSS ที่ local ต่อ component โดยใช้ selector ธรรมดา — ไม่มี naming convention ไม่มี CSS-in-JS เมื่อคุณตั้งใจจะให้มี rule แบบ global คุณ opt out ด้วย :global(...):

<style>
:global(body) { margin: 0; } /* escape the scope on purpose */
.card :global(a) { color: teal; } /* scoped .card, global descendant a */
</style>

ใส่ lang="ts" ที่ script tag เพื่อเขียน TypeScript — compiler จะ type-check แล้ว strip type ออก:

<script lang="ts">
let count: number = $state(0);
function inc(): void { count++; }
</script>

อย่างอื่นไม่เปลี่ยน; runes ถูก type ($state<T>) และ props ได้ typed interface (บทเรียนถัดไป) tooling ของ Svelte (svelte-check) type-check ไฟล์ .svelte รวมถึง markup ด้วย

สามส่วนของไฟล์ .svelte คืออะไร?
โดย default block `<style>` ของ component apply ที่ไหน?
ทำอย่างไรให้ style rule apply แบบ global โดยตั้งใจ?
ใช้ TypeScript ใน Svelte component อย่างไร?