Skip to content

Commit fd8b212

Browse files
authored
docs: Svelte docs (#41)
* overview * getting started * component fundamentals * basic markup * control flow * snippets * styles and classes * transitions and animations (WIP, needs motion and tweened, reference should have more details so we can point to it) * actions WIP (add $effect) * bindings * special elements * data fetching (WIP, what else can we put there?) * stores * imperative component api * reactivity fundamentals * contex * lifecycle hooks * state * debugging * fix * more details on $state.is, closes sveltejs/svelte#12167 * side effects * typescript related: sveltejs/svelte#11502 * custom elements * events
1 parent cbad133 commit fd8b212

23 files changed

+3860
-9
lines changed

apps/svelte.dev/content/docs/svelte/01-introduction/01-overview.md

+19-4
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,25 @@ title: Overview
66
- A few code examples to have a very rough understanding of how Svelte code looks like
77
- Jump off points to tutorial, SvelteKit etc
88

9-
## One
9+
Svelte is a web UI framework that uses a compiler to turn declarative component code like this...
1010

11-
TODO
11+
```svelte
12+
<!--- file: App.svelte --->
13+
<script lang="ts">
14+
let count = $state(0);
1215
13-
## Two
16+
function increment() {
17+
count += 1;
18+
}
19+
</script>
1420
15-
TODO
21+
<button onclick={increment}>
22+
clicks: {count}
23+
</button>
24+
```
25+
26+
...into tightly optimized JavaScript that updates the document when state like count changes. Because the compiler can 'see' where count is referenced, the generated code is highly efficient, and because we're hijacking syntax like `$state(...)` and `=` instead of using cumbersome APIs, you can write less code.
27+
28+
Besides being fun to work with, Svelte offers a lot of features built-in, such as animations and transitions. Once you've written your first components you can reach for our batteries included metaframework [SvelteKit](/docs/kit) which provides you with an opinionated router, data loading and more.
29+
30+
If you're new to Svelte, visit the [interactive tutorial](/tutorial) before consulting this documentation. You can try Svelte online using the [REPL](/repl). Alternatively, if you'd like a more fully-featured environment, you can try Svelte on [StackBlitz](https://sveltekit.new).

apps/svelte.dev/content/docs/svelte/01-introduction/02-getting-started.md

+31
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,34 @@ title: Getting started
66
- `npm create vite@latest`, describe that it scaffolds Svelte SPA powered by Vite
77
- mention `svelte-add`
88
- Jump off points to tutorial, SvelteKit etc
9+
10+
## Start a new project
11+
12+
We recommend using [SvelteKit](https://kit.svelte.dev/), the official application framework from the Svelte team:
13+
14+
```
15+
npm create svelte@latest myapp
16+
cd myapp
17+
npm install
18+
npm run dev
19+
```
20+
21+
SvelteKit will handle calling [the Svelte compiler](https://www.npmjs.com/package/svelte) to convert your `.svelte` files into `.js` files that create the DOM and `.css` files that style it. It also provides all the other pieces you need to build a web application such as a development server, routing, deployment, and SSR support. [SvelteKit](https://kit.svelte.dev/) uses [Vite](https://vitejs.dev/) to build your code.
22+
23+
Don't worry if you don't know Svelte yet! You can ignore all the nice features SvelteKit brings on top for now and dive into it later.
24+
25+
### Alternatives to SvelteKit
26+
27+
If you don't want to use SvelteKit for some reason, you can also use Svelte with Vite (but without SvelteKit) by running `npm create vite@latest` and selecting the `svelte` option. With this, `npm run build` will generate HTML, JS and CSS files inside the `dist` directory thanks using [vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte). In most cases, you will probably need to [choose a routing library](faq#is-there-a-router) as well.
28+
29+
Alternatively, there are plugins for [Rollup](https://github.com/sveltejs/rollup-plugin-svelte), [Webpack](https://github.com/sveltejs/svelte-loader) [and a few others](https://sveltesociety.dev/packages?category=build-plugins) to handle Svelte compilation — which will output `.js` and `.css` that you can insert into your HTML — but setting up SSR with them requires more manual work.
30+
31+
## Editor tooling
32+
33+
The Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) and there are integrations with various other [editors](https://sveltesociety.dev/resources#editor-support) and tools as well.
34+
35+
You can also check your code from the command line using [svelte-check](https://www.npmjs.com/package/svelte-check) (using the Svelte or Vite CLI setup will install this for you).
36+
37+
## Getting help
38+
39+
Don't be shy about asking for help in the [Discord chatroom](https://svelte.dev/chat)! You can also find answers on [Stack Overflow](https://stackoverflow.com/questions/tagged/svelte).
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
---
2+
title: Reactivity fundamentals
3+
---
4+
5+
Reactivity is at the heart of interactive UIs. When you click a button, you expect some kind of response. It's your job as a developer to make this happen. It's Svelte's job to make your job as intuitive as possible, by providing a good API to express reactive systems.
6+
7+
## Runes
8+
9+
Svelte 5 uses _runes_, a powerful set of primitives for controlling reactivity inside your Svelte components and inside `.svelte.js` and `.svelte.ts` modules.
10+
11+
Runes are function-like symbols that provide instructions to the Svelte compiler. You don't need to import them from anywhere — when you use Svelte, they're part of the language.
12+
13+
The following sections introduce the most important runes for declare state, derived state and side effects at a high level. For more details refer to the later sections on [state](/docs/svelte/runes/state) and [side effects](/docs/svelte/runes/side-effects).
14+
15+
## `$state`
16+
17+
Reactive state is declared with the `$state` rune:
18+
19+
```svelte
20+
<script>
21+
let count = $state(0);
22+
</script>
23+
24+
<button onclick={() => count++}>
25+
clicks: {count}
26+
</button>
27+
```
28+
29+
You can also use `$state` in class fields (whether public or private):
30+
31+
```js
32+
// @errors: 7006 2554
33+
class Todo {
34+
done = $state(false);
35+
text = $state();
36+
37+
constructor(text) {
38+
this.text = text;
39+
}
40+
}
41+
```
42+
43+
## `$derived`
44+
45+
Derived state is declared with the `$derived` rune:
46+
47+
```svelte
48+
<script>
49+
let count = $state(0);
50+
let doubled = $derived(count * 2);
51+
</script>
52+
53+
<button onclick={() => count++}>
54+
{doubled}
55+
</button>
56+
57+
<p>{count} doubled is {doubled}</p>
58+
```
59+
60+
The expression inside `$derived(...)` should be free of side-effects. Svelte will disallow state changes (e.g. `count++`) inside derived expressions.
61+
62+
As with `$state`, you can mark class fields as `$derived`.
63+
64+
## `$effect`
65+
66+
To run _side-effects_ when the component is mounted to the DOM, and when values change, we can use the `$effect` rune ([demo](/#H4sIAAAAAAAAE31T24rbMBD9lUG7kAQ2sbdlX7xOYNk_aB_rQhRpbAsU2UiTW0P-vbrYubSlYGzmzMzROTPymdVKo2PFjzMzfIusYB99z14YnfoQuD1qQh-7bmdFQEonrOppVZmKNBI49QthCc-OOOH0LZ-9jxnR6c7eUpOnuv6KeT5JFdcqbvbcBcgDz1jXKGg6ncFyBedYR6IzLrAZwiN5vtSxaJA-EzadfJEjKw11C6GR22-BLH8B_wxdByWpvUYtqqal2XB6RVkG1CoHB6U1WJzbnYFDiwb3aGEdDa3Bm1oH12sQLTcNPp7r56m_00mHocSG97_zd7ICUXonA5fwKbPbkE2ZtMJGGVkEdctzQi4QzSwr9prnFYNk5hpmqVuqPQjNnfOJoMF22lUsrq_UfIN6lfSVyvQ7grB3X2mjMZYO3XO9w-U5iLx42qg29md3BP_ni5P4gy9ikTBlHxjLzAtPDlyYZmRdjAbGq7HprEQ7p64v4LU_guu0kvAkhBim3nMplWl8FreQD-CW20aZR0wq12t-KqDWeBywhvexKC3memmDwlHAv9q4Vo2ZK8KtK0CgX7u9J8wXbzdKv-nRnfF_2baTqlYoWUF2h5efl9-n0O6koAMAAA==)):
67+
68+
```svelte
69+
<script>
70+
let size = $state(50);
71+
let color = $state('#ff3e00');
72+
73+
let canvas;
74+
75+
$effect(() => {
76+
const context = canvas.getContext('2d');
77+
context.clearRect(0, 0, canvas.width, canvas.height);
78+
79+
// this will re-run whenever `color` or `size` change
80+
context.fillStyle = color;
81+
context.fillRect(0, 0, size, size);
82+
});
83+
</script>
84+
85+
<canvas bind:this={canvas} width="100" height="100" />
86+
```
87+
88+
The function passed to `$effect` will run when the component mounts, and will re-run after any changes to the values it reads that were declared with `$state` or `$derived` (including those passed in with `$props`). Re-runs are batched (i.e. changing `color` and `size` in the same moment won't cause two separate runs), and happen after any DOM updates have been applied.

apps/svelte.dev/content/docs/svelte/02-template-syntax/01-component-fundamentals.md

+178
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,181 @@ title: Component fundamentals
44

55
- script (module) / template / style (rough overview)
66
- `$props` / `$state` (in the context of components)
7+
8+
Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML.
9+
10+
All three sections — script, styles and markup — are optional.
11+
12+
```svelte
13+
<script>
14+
// logic goes here
15+
</script>
16+
17+
<!-- markup (zero or more items) goes here -->
18+
19+
<style>
20+
/* styles go here */
21+
</style>
22+
```
23+
24+
## &lt;script&gt;
25+
26+
A `<script>` block contains JavaScript (or TypeScript, when adding the `lang="ts"` attribute) that runs when a component instance is created. Variables declared (or imported) at the top level are 'visible' from the component's markup.
27+
28+
### Public API of a component
29+
30+
Svelte uses the `$props` rune to declare _properties_ or _props_, which means describing the public interface of the component which becomes accessible to consumers of the component.
31+
32+
> `$props` is one of several runes, which are special hints for Svelte's compiler to make things reactive.
33+
34+
```svelte
35+
<script>
36+
let { foo, bar, baz } = $props();
37+
38+
// Values that are passed in as props
39+
// are immediately available
40+
console.log({ foo, bar, baz });
41+
</script>
42+
```
43+
44+
You can specify a fallback value for a prop. It will be used if the component's consumer doesn't specify the prop on the component when instantiating the component, or if the passed value is `undefined` at some point.
45+
46+
```svelte
47+
<script>
48+
let { foo = 'optional default initial value' } = $props();
49+
</script>
50+
```
51+
52+
To get all properties, use rest syntax:
53+
54+
```svelte
55+
<script>
56+
let { a, b, c, ...everythingElse } = $props();
57+
</script>
58+
```
59+
60+
You can use reserved words as prop names.
61+
62+
```svelte
63+
<script>
64+
// creates a `class` property, even
65+
// though it is a reserved word
66+
let { class: className } = $props();
67+
</script>
68+
```
69+
70+
If you're using TypeScript, you can declare the prop types:
71+
72+
```svelte
73+
<script lang="ts">
74+
interface Props {
75+
a: number;
76+
b: boolean;
77+
c: string;
78+
[key: string]: unknown;
79+
}
80+
81+
let { a, b, c, ...everythingElse }: Props = $props();
82+
</script>
83+
```
84+
85+
If you export a `const`, `class` or `function`, it is readonly from outside the component.
86+
87+
```svelte
88+
<script>
89+
export const thisIs = 'readonly';
90+
91+
export function greet(name) {
92+
alert(`hello ${name}!`);
93+
}
94+
</script>
95+
```
96+
97+
Readonly props can be accessed as properties on the element, tied to the component using [`bind:this` syntax](/docs/component-directives#bind-this).
98+
99+
### Reactive variables
100+
101+
To change component state and trigger a re-render, just assign to a locally declared variable that was declared using the `$state` rune.
102+
103+
Update expressions (`count += 1`) and property assignments (`obj.x = y`) have the same effect.
104+
105+
```svelte
106+
<script>
107+
let count = $state(0);
108+
109+
function handleClick() {
110+
// calling this function will trigger an
111+
// update if the markup references `count`
112+
count = count + 1;
113+
}
114+
</script>
115+
```
116+
117+
Svelte's `<script>` blocks are run only when the component is created, so assignments within a `<script>` block are not automatically run again when a prop updates.
118+
119+
```svelte
120+
<script>
121+
let { person } = $props();
122+
// this will only set `name` on component creation
123+
// it will not update when `person` does
124+
let { name } = person;
125+
</script>
126+
```
127+
128+
If you'd like to react to changes to a prop, use the `$derived` or `$effect` runes instead.
129+
130+
```svelte
131+
<script>
132+
let count = $state(0);
133+
134+
let double = $derived(count * 2);
135+
136+
$effect(() => {
137+
if (count > 10) {
138+
alert('Too high!');
139+
}
140+
});
141+
</script>
142+
```
143+
144+
For more information on reactivity, read the documentation around runes.
145+
146+
## &lt;script context="module"&gt;
147+
148+
A `<script>` tag with a `context="module"` attribute runs once when the module first evaluates, rather than for each component instance. Values declared in this block are accessible from a regular `<script>` (and the component markup) but not vice versa.
149+
150+
You can `export` bindings from this block, and they will become exports of the compiled module.
151+
152+
You cannot `export default`, since the default export is the component itself.
153+
154+
```svelte
155+
<script context="module">
156+
let totalComponents = 0;
157+
158+
// the export keyword allows this function to imported with e.g.
159+
// `import Example, { alertTotal } from './Example.svelte'`
160+
export function alertTotal() {
161+
alert(totalComponents);
162+
}
163+
</script>
164+
165+
<script>
166+
totalComponents += 1;
167+
console.log(`total number of times this component has been created: ${totalComponents}`);
168+
</script>
169+
```
170+
171+
## &lt;style&gt;
172+
173+
CSS inside a `<style>` block will be scoped to that component.
174+
175+
```svelte
176+
<style>
177+
p {
178+
/* this will only affect <p> elements in this component */
179+
color: burlywood;
180+
}
181+
</style>
182+
```
183+
184+
For more information regarding styling, read the documentation around [styles and classes](styles-and-classes).

0 commit comments

Comments
 (0)