Svelte components and files

Svelte · Essentials · 10 min

Everything in Svelte is a component file; knowing its three parts is the starting point for all the rest.

Svelte is a compiler: you write .svelte files and the build step (a Vite plugin) turns each into plain JavaScript that creates and updates the DOM directly. There is no virtual DOM and very little runtime code.

Start a project with npx sv create my-app, which scaffolds a SvelteKit app (recommended even for single-page apps), or use the Vite Svelte template for a plain Svelte setup.

A component file has three optional parts:

  • <script> — component logic. Runs once per component instance when it is created. Add lang="ts" for TypeScript.
  • Markup — HTML with {expressions} in braces: <h1>Hello {name}!</h1>, attributes like src={url}, and the shorthand {src} when the name matches.
  • <style> — CSS that is scoped to this component automatically (Svelte adds a hashed class to its elements).

To use another component, import it and write it as a capitalised tag: import Card from './Card.svelte' then <Card />. Lower-case tags are always HTML elements.

Outside SvelteKit, you mount the root component yourself with mount(App, { target: document.getElementById('app') }) from svelte; SvelteKit does this for you.

.svelte.js and .svelte.ts files are ordinary modules that can also use runes, which you will meet when sharing state.

Example

<!-- App.svelte -->
<script>
  import Card from './Card.svelte';
  let name = 'world';
  let logo = '/svelte.png';
</script>

<h1>Hello {name.toUpperCase()}!</h1>     <!-- Hello WORLD! -->
<img src={logo} alt="logo" />
<Card />

<style>
  h1 { color: #d63a0f; }   /* scoped: other components' h1s are unaffected */
</style>

<!-- main.js (plain Vite setup; SvelteKit does this for you)
import { mount } from 'svelte';
import App from './App.svelte';
mount(App, { target: document.getElementById('app') });
-->

Remember

  • A .svelte file = <script> + markup with {expressions} + scoped <style>
  • Svelte compiles components to direct DOM code; no virtual DOM
  • npx sv create scaffolds a SvelteKit project; mount() boots plain Svelte

Watch out for

  • Naming a component in lowercase (<card />); it is then treated as an HTML element.

Check yourself

  1. How does Svelte make `<style>` rules apply only to the component's own elements?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: svelte.dev/docs/svelte/svelte-files