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. Addlang="ts"for TypeScript.- Markup — HTML with
{expressions}in braces:<h1>Hello {name}!</h1>, attributes likesrc={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
.sveltefile =<script>+ markup with{expressions}+ scoped<style> - Svelte compiles components to direct DOM code; no virtual DOM
npx sv createscaffolds a SvelteKit project;mount()boots plain Svelte
Watch out for
- Naming a component in lowercase (
<card />); it is then treated as an HTML element.