Skip to content
Merged

Docs #469

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions apps/svelte.dev/content/docs/svelte/01-introduction/01-overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,29 @@
title: Overview
---

- Short intro to what Svelte is and why it's the best ever
- A few code examples to have a very rough understanding of how Svelte code looks like
- Jump off points to tutorial, SvelteKit etc

Svelte is a web UI framework that uses a compiler to turn declarative component code like this...
Svelte is a framework for building user interfaces on the web. It uses a compiler to turn declarative components written in HTML, CSS and JavaScript...

```svelte
<!--- file: App.svelte --->
<script lang="ts">
let count = $state(0);

function increment() {
count += 1;
<script>
function greet() {
alert('Welcome to Svelte!');
}
</script>

<button onclick={increment}>
clicks: {count}
</button>
<button onclick={greet}>click me</button>

<style>
button {
font-size: 2em;
}
</style>
```

...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.
...into lean, tightly optimized JavaScript.

You can use it to build anything on the web, from standalone components to ambitious full stack apps (using Svelte's companion application framework, [SvelteKit](../kit)) and everything in between.

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](../kit) which provides you with an opinionated router, data loading and more.
These pages serve as reference documentation. If you're new to Svelte, we recommend starting with the [interactive tutorial](/tutorial) and coming back here when you have questions.

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).
You can also try Svelte online in the [playground](/playground) or, if you need a more fully-featured environment, on [StackBlitz](https://sveltekit.new).
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,27 @@
title: Getting started
---

- `npm create svelte@latest`, describe that it scaffolds SvelteKit project
- `npm create vite@latest`, describe that it scaffolds Svelte SPA powered by Vite
- mention `svelte-add`
- Jump off points to tutorial, SvelteKit etc

## Start a new project

We recommend using [SvelteKit](https://kit.svelte.dev/), the official application framework from the Svelte team:
We recommend using [SvelteKit](https://kit.svelte.dev/), the official application framework from the Svelte team powered by [Vite](https://vite.dev/):

```
npm create svelte@latest myapp
npx sv create myapp
cd myapp
npm install
npm run dev
```

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.

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.

### Alternatives to SvelteKit

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.
You can also use Svelte directly with Vite 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 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.

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.
There are also 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), but we recommend Vite.

## Editor tooling

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.

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).
You can also check your code from the command line using [sv check](https://github.com/sveltejs/cli).

## Getting help

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
title: .svelte files
---

Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML.

All three sections — script, styles and markup — are optional.

<!-- prettier-ignore -->
```svelte
/// file: MyComponent.svelte
<script module>
// module-level logic goes here
// (you will rarely use this)
</script>

<script>
// instance-level logic goes here
</script>

<!-- markup (zero or more items) goes here -->

<style>
/* styles go here */
</style>
```

## `<script>`

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 can be referenced in the component's markup.

In addition to normal JavaScript, you can use _runes_ to declare [component props]($props) and add reactivity to your component. Runes are covered in the next section.

<!-- TODO describe behaviour of `export` -->

## `<script module>`

A `<script>` tag with a `module` attribute runs once when the module first evaluates, rather than for each component instance. Variables declared in this block can be referenced elsewhere in the component, but not vice versa.

You can `export` bindings from this block, and they will become exports of the compiled module. You cannot `export default`, since the default export is the component itself.

```svelte
<script module>
let total = 0;
</script>

<script>
total += 1;
console.log(`instantiated ${total} times`);
</script>
```

## `<style>`

CSS inside a `<style>` block will be scoped to that component.

```svelte
<style>
p {
/* this will only affect <p> elements in this component */
color: burlywood;
}
</style>
```

For more information regarding styling, read the documentation around [styles and classes](styles-and-classes).
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
title: .svelte.js and .svelte.ts files
---

Besides `.svelte` files, Svelte also operates on `.svelte.js` and `.svelte.ts` files.

These behave like any other `.js` or `.ts` module, except that you can use runes. This is useful for creating reusable reactive logic, or sharing reactive state across your app.
Original file line number Diff line number Diff line change
@@ -1,30 +1,7 @@
---
title: Component fundamentals
title: Public API of a component
---

- script (module) / template / style (rough overview)
- `$props` / `$state` (in the context of components)

Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML.

All three sections — script, styles and markup — are optional.

```svelte
<script>
// logic goes here
</script>

<!-- markup (zero or more items) goes here -->

<style>
/* styles go here */
</style>
```

## `<script>`

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.

### Public API of a component

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.
Expand Down Expand Up @@ -160,43 +137,3 @@ If you'd like to react to changes to a prop, use the `$derived` or `$effect` run
```

For more information on reactivity, read the documentation around runes.

## `<script module>`

A `<script>` tag with a `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.

You can `export` bindings from this block, and they will become exports of the compiled module.

You cannot `export default`, since the default export is the component itself.

```svelte
<script module>
let totalComponents = 0;

// the export keyword allows this function to imported with e.g.
// `import Example, { alertTotal } from './Example.svelte'`
export function alertTotal() {
alert(totalComponents);
}
</script>

<script>
totalComponents += 1;
console.log(`total number of times this component has been created: ${totalComponents}`);
</script>
```

## `<style>`

CSS inside a `<style>` block will be scoped to that component.

```svelte
<style>
p {
/* this will only affect <p> elements in this component */
color: burlywood;
}
</style>
```

For more information regarding styling, read the documentation around [styles and classes](styles-and-classes).
21 changes: 21 additions & 0 deletions apps/svelte.dev/content/docs/svelte/02-runes/01-what-are-runes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
title: What are runes?
---

> [!NOTE] **rune** /ro͞on/ _noun_
>
> A letter or mark used as a mystical or magic symbol.

Runes are symbols that you use in `.svelte` and `.svelte.js`/`.svelte.ts` files to control the Svelte compiler. If you think of Svelte as a language, runes are part of the syntax — they are _keywords_.

Runes have a `$` prefix and look like functions:

```js
let message = $state('hello');
```

They differ from normal JavaScript functions in important ways, however:

- You don't need to import them — they are part of the language
- They're not values — you can't assign them to a variable or pass them as arguments to a function
- Just like JavaScript keywords, they are only valid in certain positions (the compiler will help you if you put them in the wrong place)
127 changes: 127 additions & 0 deletions apps/svelte.dev/content/docs/svelte/02-runes/02-$state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
---
title: $state
---

The `$state` rune allows you to create _reactive state_, which means that your UI _reacts_ when it changes.

```svelte
<script>
let count = $state(0);
</script>

<button onclick={() => count++}>
clicks: {count}
</button>
```

Unlike other frameworks you may have encountered, there is no API for interacting with state — `count` is just a number, rather than an object or a function, and you can update it like you would update any other variable.

### Deep state

If `$state` is used with an array or a simple object, the result is a deeply reactive _state proxy_. [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) allow Svelte to run code when you read or write properties, including via methods like `array.push(...)`, triggering granular updates.

State is proxified recursively until Svelte finds something other than an array or simple object. In a case like this...

```js
let todos = $state([
{
done: false,
text: 'add more todos'
}
]);
```

...modifying an individual todo's property will trigger updates to anything in your UI that depends on that specific property:

```js
// @filename: ambient.d.ts
declare global {
const todos: Array<{ done: boolean, text: string }>
}

// @filename: index.js
// ---cut---
todos[0].done = !todos[0].done;
```

If you push a new object to the array, it will also be proxified:

```js
// @filename: ambient.d.ts
declare global {
const todos: Array<{ done: boolean, text: string }>
}

// @filename: index.js
// ---cut---
todos.push({
done: false,
text: 'eat lunch'
});
```

> [!NOTE] When you update properties of proxies, the original object is _not_ mutated.

### Classes

You can also use `$state` in class fields (whether public or private):

```js
// @errors: 7006 2554
class Todo {
done = $state(false);
text = $state();

constructor(text) {
this.text = text;
}

reset() {
this.text = '';
this.done = false;
}
}
```

> [!NOTE] The compiler transforms `done` and `text` into `get`/`set` methods on the class prototype referencing private fields.

## `$state.raw`

In cases where you don't want objects and arrays to be deeply reactive you can use `$state.raw`.

State declared with `$state.raw` cannot be mutated; it can only be _reassigned_. In other words, rather than assigning to a property of an object, or using an array method like `push`, replace the object or array altogether if you'd like to update it:

```js
let person = $state.raw({
name: 'Heraclitus',
age: 49
});

// this will have no effect (and will throw an error in dev)
person.age += 1;

// this will work, because we're creating a new person
person = {
name: 'Heraclitus',
age: 50
};
```

This can improve performance with large arrays and objects that you weren't planning to mutate anyway, since it avoids the cost of making them reactive. Note that raw state can _contain_ reactive state (for example, a raw array of reactive objects).

## `$state.snapshot`

To take a static snapshot of a deeply reactive `$state` proxy, use `$state.snapshot`:

```svelte
<script>
let counter = $state({ count: 0 });

function onclick() {
// Will log `{ count: ... }` rather than `Proxy { ... }`
console.log($state.snapshot(counter));
}
</script>
```

This is handy when you want to pass some state to an external library or API that doesn't expect a proxy, such as `structuredClone`.
Loading
Loading