diff --git a/apps/svelte.dev/.env b/apps/svelte.dev/.env index 9b1319a6f1..43b6ea5cb7 100644 --- a/apps/svelte.dev/.env +++ b/apps/svelte.dev/.env @@ -3,3 +3,6 @@ SUPABASE_KEY= GITHUB_CLIENT_ID= GITHUB_CLIENT_SECRET= + +# disable prerendering with `PRERENDER=false pnpm build` — this is useful for speeding up builds when previewing locally +PRERENDER=true diff --git a/apps/svelte.dev/.gitignore b/apps/svelte.dev/.gitignore index 321615eddf..82cbd2da73 100644 --- a/apps/svelte.dev/.gitignore +++ b/apps/svelte.dev/.gitignore @@ -6,6 +6,8 @@ /src/routes/_home/Supporters/contributors.js /src/routes/_home/Supporters/donors.jpg /src/routes/_home/Supporters/donors.js +/scripts/svelte-template +/static/svelte-template.json # git-repositories of synced docs go here /repos/ diff --git a/apps/svelte.dev/README.md b/apps/svelte.dev/README.md index eab3acafcd..9658426470 100644 --- a/apps/svelte.dev/README.md +++ b/apps/svelte.dev/README.md @@ -35,3 +35,11 @@ When writing content for the tutorial, you need to be aware of the differences o ### Dependencies If you look in the site's package.json you'll notice several dependencies that don't appear to be used, such as `@testing-library/svelte`. These are present because they're referenced in the docs, and Twoslash needs to be able to find type definitions in order to typecheck snippets. Installing the dependencies was deemed preferable to faking it with `declare module`, since we're liable to end up with fictional types that way. + +### Prerendering + +Most of the site is prerendered. Since that involves some fairly expensive work, it can take a while. To build the site _without_ prerendering — for example, because you need to debug an issue that's affecting production builds — set the `PRERENDER` environment variable to `false`: + +```bash +PRERENDER=false pnpm build +``` diff --git a/apps/svelte.dev/content/blog/2021-04-01-whats-new-in-svelte-april-2021.md b/apps/svelte.dev/content/blog/2021-04-01-whats-new-in-svelte-april-2021.md index fa948654ce..fd907fb29a 100644 --- a/apps/svelte.dev/content/blog/2021-04-01-whats-new-in-svelte-april-2021.md +++ b/apps/svelte.dev/content/blog/2021-04-01-whats-new-in-svelte-april-2021.md @@ -14,7 +14,7 @@ authorURL: https://dreamindani.com ## SvelteとLanguageツールの新着情報(New in Svelte & Language Tools) -- Slotted components (``を含む) を使用すると、コンポーネントの利用者が特定のスロットにリッチなコンテンツを割り当てることができます (**Svelte 3.35.0, Language Tools [104.5.0](https://github.com/sveltejs/language-tools/releases/tag/extensions-104.5.0)**, [docs](/docs/special-elements#svelte-fragment) と [tutorial](https://svelte.jp/tutorial/svelte-fragment) をチェックしてみてください) +- Slotted components (``を含む) を使用すると、コンポーネントの利用者が特定のスロットにリッチなコンテンツを割り当てることができます (**Svelte 3.35.0, Language Tools [104.5.0](https://github.com/sveltejs/language-tools/releases/tag/extensions-104.5.0)**) - Linked editing がSvelteファイル内のHTMLで機能するようになりました (**Language Tools, [104.6.0](https://github.com/sveltejs/language-tools/releases/tag/extensions-104.6.0)**) - 型定義 `svelte.d.ts` が正常に解決されるようになり、ライブラリの作成者がSvelteコンポーネントと一緒に型定義を配布できるようになりました (**Language Tools, [104.7.0](https://github.com/sveltejs/language-tools/releases/tag/extensions-104.7.0)**) - ViteでSvelteを使用するのに [vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte) が利用可能になりました。`npm init @vitejs/app` はこのプラグインを使用したSvelteオプションが含まれています。 diff --git a/apps/svelte.dev/content/blog/2023-02-21-streaming-snapshots-sveltekit.md b/apps/svelte.dev/content/blog/2023-02-21-streaming-snapshots-sveltekit.md index a1ebcc05a9..70e3e1d636 100644 --- a/apps/svelte.dev/content/blog/2023-02-21-streaming-snapshots-sveltekit.md +++ b/apps/svelte.dev/content/blog/2023-02-21-streaming-snapshots-sveltekit.md @@ -29,11 +29,7 @@ export const load: PageServerLoad = () => { }; ``` -<<<<<<< HEAD -SvelteKit は自動的にこの `fetchPost` の呼び出しを await してからページのレンダリングを開始します。なぜならそれがトップレベルだからです。しかし、ネストした `fetchComments` の呼び出しが完了するのは待ちません – ページはレンダリングされ、`data.streamed.comments` はリクエストが完了すると解決する promise となります。`+page.svelte` で、Svelte の [await block](/docs/logic-blocks#await) を使用してロード中の状態を表示することもできます: -======= -SvelteKit will automatically await the `fetchPost` call before it starts rendering the page, since it’s at the top level. However, it won’t wait for the nested `fetchComments` call to complete – the page will render and `data.streamed.comments` will be a promise that will resolve as the request completes. We can show a loading state in the corresponding `+page.svelte` using Svelte’s [await block](/docs/svelte/await): ->>>>>>> sveltejs/main +SvelteKit は自動的にこの `fetchPost` の呼び出しを await してからページのレンダリングを開始します。なぜならそれがトップレベルだからです。しかし、ネストした `fetchComments` の呼び出しが完了するのは待ちません – ページはレンダリングされ、`data.streamed.comments` はリクエストが完了すると解決する promise となります。`+page.svelte` で、Svelte の [await block](/docs/svelte/await) を使用してロード中の状態を表示することもできます: ```svelte @@ -51,6 +52,8 @@ Pages can receive data from `load` functions via the `data` prop. ``` > [!LEGACY] +> `PageProps` was added in 2.16.0. In earlier versions, you had to type the `data` property manually with `PageData` instead, see [$types](#\$types). +> > Svelte 4 では、代わりに `export let data` を使用します > [!NOTE] SvelteKit では、ルート(routes)間のナビゲーションに、フレームワーク固有の `` コンポーネントではなく、`` 要素を使用します。 @@ -132,12 +135,15 @@ export async function load({ params }) { ```svelte -

{$page.status}: {$page.error.message}

+

{page.status}: {page.error.message}

``` +> [!LEGACY] +> `$app/state` was added in SvelteKit 2.12. If you're using an earlier version or are using Svelte 4, use `$app/stores` instead. + SvelteKit は、ツリーを上がって (walk up the tree) 最も近いエラー境界 (error boundary) を探します — もし上記のファイルが存在しない場合は、デフォルトのエラーページをレンダリングする前に `src/routes/blog/+error.svelte` を探しに行き、その次に `src/routes/+error.svelte` を探します。もしそれも失敗した場合は (または、最上位の `+error` の '上に' 位置する最上位の `+layout` の `load` 関数からエラーがスローされた場合)、SvelteKit は静的なフォールバックエラーページをレンダリングします。これは `src/error.html` ファイルを作成することでカスタマイズ可能です。 `+layout(.server).js` の `load` 関数の内側でエラーが発生した場合、ツリーの中で最も近くにあるエラー境界はそのレイアウトの上位にある `+error.svelte` ファイルです (隣ではありません)。 @@ -169,7 +175,7 @@ SvelteKit は、ツリーを上がって (walk up the tree) 最も近いエラ …しかし、お望みのマークアップ(markup)、スタイル(styles)、動作(behaviour)を追加することができます。唯一の要求事項は、コンポーネントにページコンテンツのための `@render` タグを含めることです。例えば、nav bar を追加してみましょう: ```svelte - + @@ -209,7 +215,7 @@ SvelteKit は、ツリーを上がって (walk up the tree) 最も近いエラ ```svelte @@ -224,6 +230,9 @@ SvelteKit は、ツリーを上がって (walk up the tree) 最も近いエラ {@render children()} ``` +> [!LEGACY] +> `LayoutProps` was added in 2.16.0. In earlier versions, you had to [type the properties manually instead](#\$types). + `data` がどのように入力されるかは、すぐ下の次のセクションにある `+layout.js` の例を見ればわかります。 デフォルトでは、各レイアウトはその上にあるレイアウトを継承します。そうしたくない場合は、[advanced layouts](advanced-routing#Advanced-layouts) が役に立つでしょう。 @@ -252,7 +261,7 @@ export function load() { ```svelte ``` -`load` 関数に `PageLoad`、`PageServerLoad`、`LayoutLoad`、`LayoutServerLoad` (それぞれ `+page.js`、`+page.server.js`、`+layout.js`、`+layout.server.js`) というアノテーションを付けると、`params` と戻り値が正しく型付けされることが保証されるでしょう。 +> [!NOTE] +> The `PageProps` and `LayoutProps` types, added in 2.16.0, are a shortcut for typing the `data` prop as `PageData` or `LayoutData`, as well as other props, such as `form` for pages, or `children` for layouts. In earlier versions, you had to type these properties manually. For example, for a page: +> +> ```js +> /// file: +page.svelte +> /** @type {{ data: import('./$types').PageData, form: import('./$types').ActionData }} */ +> let { data, form } = $props(); +> ``` +> +> Or, for a layout: +> +> ```js +> /// file: +layout.svelte +> /** @type {{ data: import('./$types').LayoutData, children: Snippet }} */ +> let { data, children } = $props(); +> ``` + +`load` 関数に `PageLoad`、`PageServerLoad`、`LayoutLoad`、`LayoutServerLoad` (それぞれ `+page.js`、`+page.server.js`、`+layout.js`、`+layout.server.js`) というアノテーションを付けると、`params` と戻り値が正しく型付けされることが保証されます。 VS Code や、language server protocol と TypeScript plugin をサポートする IDE を使用している場合は、これらの型を _完全に_ 省略することができます! Svelte の IDE ツール類があなたのために正しい型を挿入してくれるので、あなたはご自身で型を書くことなく型チェックすることができます。これはコマンドラインツール `svelte-check` でも機能します。 diff --git a/apps/svelte.dev/content/docs/kit/20-core-concepts/20-load.md b/apps/svelte.dev/content/docs/kit/20-core-concepts/20-load.md index 0588058bab..d67ad47363 100644 --- a/apps/svelte.dev/content/docs/kit/20-core-concepts/20-load.md +++ b/apps/svelte.dev/content/docs/kit/20-core-concepts/20-load.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Loading data --- @@ -24,7 +25,7 @@ export function load({ params }) { ```svelte @@ -33,7 +34,14 @@ export function load({ params }) { ``` > [!LEGACY] -> Svelte 4 では、代わりに `export let data` を使います +> Before version 2.16.0, the props of a page and layout had to be typed individually: +> ```js +> /// file: +page.svelte +> /** @type {{ data: import('./$types').PageData }} */ +> let { data } = $props(); +> ``` +> +> Svelte 4 では、代わりに `export let data` を使います。 生成される `$types` モジュールのおかげで、完全な型安全性を確保できます。 @@ -88,7 +96,7 @@ export async function load() { ```svelte @@ -111,19 +119,27 @@ export async function load() { ``` +> [!LEGACY] +> `LayoutProps` was added in 2.16.0. In earlier versions, properties had to be typed individually: +> ```js +> /// file: +layout.svelte +> /** @type {{ data: import('./$types').LayoutData, children: Snippet }} */ +> let { data, children } = $props(); +> ``` + レイアウトの `load` 関数から返されたデータは、子の `+layout.svelte` コンポーネントやそのレイアウトに属する `+page.svelte` コンポーネントでも利用可能です。 ```svelte /// file: src/routes/blog/[slug]/+page.svelte @@ -137,24 +153,28 @@ export async function load() { > [!NOTE] 複数の `load` 関数が同じキーを持つデータを返した場合、最後に返したものが'勝ちます'。レイアウトの `load` が `{ a: 1, b: 2 }` を返し、ページの `load` が `{ b: 3, c: 4 }` を返すと、結果は `{ a: 1, b: 3, c: 4 }` となります。 -## $page.data +## page.data `+page.svelte` コンポーネントとその上の各 `+layout.svelte` コンポーネントは、自身のデータとその親の全てのデータにアクセスすることができます。 -場合によっては、その逆も必要かもしれません — 親レイアウトからページのデータや子レイアウトのデータにアクセスする必要があるかもしれません。例えば、最上位のレイアウト(root layout)から、`+page.js` や `+page.server.js` の `load` 関数から返された `title` プロパティにアクセスしたい場合があるでしょう。これは `$page.data` で行うことができます: +場合によっては、その逆も必要かもしれません — 親レイアウトからページのデータや子レイアウトのデータにアクセスする必要があるかもしれません。例えば、最上位のレイアウト(root layout)から、`+page.js` や `+page.server.js` の `load` 関数から返された `title` プロパティにアクセスしたい場合があるでしょう。これは `page.data` で行うことができます: ```svelte - {$page.data.title} + {page.data.title} ``` -`$page.data` の型情報は `App.PageData` から提供されます。 +`page.data` の型情報は `App.PageData` から提供されます。 + +> [!LEGACY] +> `$app/state` was added in SvelteKit 2.12. If you're using an earlier version or are using Svelte 4, use `$app/stores` instead. +> It provides a `page` store with the same interface that you can subscribe to, e.g. `$page.data.title`. ## Universal vs server @@ -368,7 +388,7 @@ export async function load({ parent }) { ```svelte @@ -507,7 +527,7 @@ export async function load({ params }) { ```svelte @@ -648,7 +668,7 @@ export async function load({ fetch, depends }) {

random number: {data.number}

- + ``` ### load 関数はいつ再実行されるのか diff --git a/apps/svelte.dev/content/docs/kit/20-core-concepts/30-form-actions.md b/apps/svelte.dev/content/docs/kit/20-core-concepts/30-form-actions.md index 95d8e72d39..5dd44f79b5 100644 --- a/apps/svelte.dev/content/docs/kit/20-core-concepts/30-form-actions.md +++ b/apps/svelte.dev/content/docs/kit/20-core-concepts/30-form-actions.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Form actions --- @@ -100,9 +101,9 @@ export const actions = { > [!NOTE] 名前付き action (named action) の隣にデフォルトの action を置くことはできません。なぜなら リダイレクト無しで名前付き action (named action) に POST をすると、クエリパラメータが URL に保持され、それ以降デフォルトの POST をしようとしても以前 POST した名前付き action (named action) を通ってしまうからです。 -## action の解剖学 +## action の構造 -action はそれぞれ `RequestEvent` オブジェクトを受け取って、`request.formData()` でデータを読み込むことができます。リクエスト (例えば、cookie をセットしてユーザーをログインさせるなど) を処理したあと、action は次の更新まで、対応するページでは `form` プロパティで、アプリ全体では `$page.form` で利用可能なデータで応答することができます。 +action はそれぞれ `RequestEvent` オブジェクトを受け取って、`request.formData()` でデータを読み込むことができます。リクエスト (例えば、cookie をセットしてユーザーをログインさせるなど) を処理したあと、action は次の更新まで、対応するページでは `form` プロパティで、アプリ全体では `page.form` で利用可能なデータで応答することができます。 ```js /// file: src/routes/login/+page.server.js @@ -140,7 +141,7 @@ export const actions = { ```svelte @@ -152,11 +153,18 @@ export const actions = { ``` > [!LEGACY] -> In Svelte 4, you'd use `export let data` and `export let form` instead to declare properties +> `PageProps` was added in 2.16.0. In earlier versions, you had to type the `data` and `form` properties individually: +> ```js +> /// file: +page.svelte +> /** @type {{ data: import('./$types').PageData, form: import('./$types').ActionData }} */ +> let { data, form } = $props(); +> ``` +> +> In Svelte 4, you'd use `export let data` and `export let form` instead to declare properties. ### Validation errors -無効なデータが原因でリクエストが処理できなかった場合、再試行できるようにするために、直前に送信した form の値とともに validation error をユーザーに返すことができます。`fail` 関数は、HTTP ステータスコード (通常、validation error の場合は 400 か 422) をデータとともに返します。ステータスコードは `$page.status` から使用することができ、data は `form` から使用することができます: +無効なデータが原因でリクエストが処理できなかった場合、再試行できるようにするために、直前に送信した form の値とともに validation error をユーザーに返すことができます。`fail` 関数は、HTTP ステータスコード (通常、validation error の場合は 400 か 422) をデータとともに返します。ステータスコードは `page.status` から使用することができ、data は `form` から使用することができます: ```js /// file: src/routes/login/+page.server.js @@ -339,7 +347,7 @@ form をプログレッシブに強化する最も簡単な方法は、`use:enha @@ -352,7 +360,7 @@ form をプログレッシブに強化する最も簡単な方法は、`use:enha 引数が無い場合、`use:enhance` は、ブラウザネイティブの動作を、フルページリロードを除いてエミュレートします。それは: -- action が送信元のページと同じ場所にある場合に限り、成功レスポンスまたは不正なレスポンスに応じて、`form` プロパティと `$page.form` と `$page.status` を更新します。例えば、`
` というようなフォームの場合、`form` と `$page` は更新されません。これは、ネイティブのフォーム送信では action があるページにリダイレクトされるからです。どちらにしても更新させたい場合は、[`applyAction`](#Progressive-enhancement-Customising-use:enhance) を使用してください +- action が送信元のページと同じ場所にある場合に限り、成功レスポンスまたは不正なレスポンスに応じて、`form` プロパティと `page.form` と `page.status` を更新します。例えば、`` というようなフォームの場合、`form` プロパティと `page.form` state は更新されません。これは、ネイティブのフォーム送信では action があるページにリダイレクトされるからです。どちらにしても更新させたい場合は、[`applyAction`](#Progressive-enhancement-Customising-use:enhance) を使用してください - `` 要素をリセットします - 成功レスポンスの場合は `invalidateAll` で全てのデータを無効化・最新化(invalidate)します - リダイレクトレスポンスの場合は `goto` を呼び出します @@ -390,7 +398,7 @@ form をプログレッシブに強化する最も簡単な方法は、`use:enha @@ -411,7 +419,7 @@ form をプログレッシブに強化する最も簡単な方法は、`use:enha `applyAction(result)` の挙動は `result.type` に依存しています: -- `success`, `failure` — `$page.status` を `result.status` に設定し、`form` と `$page.form` を `result.data` で更新します (`enhance` の `update` とは対照的に、送信元がどこかは関係ありません) +- `success`, `failure` — `page.status` を `result.status` に設定し、`form` と `page.form` を `result.data` で更新します (`enhance` の `update` とは対照的に、送信元がどこかは関係ありません) - `redirect` — `goto(result.location, { invalidateAll: true })` を呼び出します - `error` — もっとも近くにある `+error` 境界を `result.error` でレンダリングします @@ -427,11 +435,12 @@ form をプログレッシブに強化する最も簡単な方法は、`use:enha import { invalidateAll, goto } from '$app/navigation'; import { applyAction, deserialize } from '$app/forms'; - /** @type {{ form: import('./$types').ActionData }} */ + /** @type {import('./$types').PageProps} */ let { form } = $props(); - /** @param {{ currentTarget: EventTarget & HTMLFormElement}} event */ + /** @param {SubmitEvent & { currentTarget: EventTarget & HTMLFormElement}} event */ async function handleSubmit(event) { + event.preventDefault(); const data = new FormData(event.currentTarget); const response = await fetch(event.currentTarget.action, { @@ -451,7 +460,7 @@ form をプログレッシブに強化する最も簡単な方法は、`use:enha } - +
``` @@ -484,7 +493,7 @@ const response = await fetch(this.action, { } - + ``` ```js diff --git a/apps/svelte.dev/content/docs/kit/20-core-concepts/40-page-options.md b/apps/svelte.dev/content/docs/kit/20-core-concepts/40-page-options.md index d28d64fd06..bbc6374a03 100644 --- a/apps/svelte.dev/content/docs/kit/20-core-concepts/40-page-options.md +++ b/apps/svelte.dev/content/docs/kit/20-core-concepts/40-page-options.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Page options --- @@ -127,6 +128,8 @@ export const ssr = false; `export const ssr = false` を最上位(root)の `+layout.js` に追加した場合、アプリ全体がクライアントのみでレンダリングされるようになり、それはつまり、本質的にはアプリを SPA にする、ということを意味します。 +> [!NOTE] Even with `ssr` set to `false`, code that relies on browser APIs should be imported in your `+page.svelte` or `+layout.svelte` file instead. This is because page options can be overriden and need to be evaluated by importing your `+page.js` or `+layout.js` file on the server (if you have a runtime) or at build time (in case of prerendering). + ## csr 通常、SvelteKit はサーバーでレンダリングされた HTML を、クライアントサイドレンダリング(CSR)されたインタラクティブなページに [ハイドレーション](glossary#Hydration) します。JavaScript を全く必要としないページもあります。多くのブログ記事や 'about' ページがこのカテゴリに入ります。このような場合は CSR を無効にすることができます: diff --git a/apps/svelte.dev/content/docs/kit/20-core-concepts/50-state-management.md b/apps/svelte.dev/content/docs/kit/20-core-concepts/50-state-management.md index c71ba82443..1a655d304a 100644 --- a/apps/svelte.dev/content/docs/kit/20-core-concepts/50-state-management.md +++ b/apps/svelte.dev/content/docs/kit/20-core-concepts/50-state-management.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: State management --- @@ -40,7 +41,7 @@ export const actions = { ## load に副作用を持たせない -同じ理由で、`load` 関数は _純粋(pure)_ であるべきです — 副作用(side-effect)を持つべきではありません (必要なときに使用する `console.log(...)` は除く)。例えば、コンポーネントで store の値を使用できるようにするために、`load` 関数の内側で store に書き込みをしたくなるかもしれません: +同じ理由で、`load` 関数は _純粋(pure)_ であるべきです — 副作用(side-effect)を持つべきではありません (必要なときに使用する `console.log(...)` は除く)。例えば、コンポーネントで store やグローバルな state の値を使用できるようにするために、`load` 関数の内側で store やグローバルな state に書き込みをしたくなるかもしれません: ```js /// file: +page.js @@ -76,31 +77,25 @@ export async function load({ fetch }) { } ``` -…そしてそのデータを必要とするコンポーネントに渡すか、[`$page.data`](load#$page.data) を使用してください。 +…そしてそのデータを必要とするコンポーネントに渡すか、[`page.data`](load#page.data) を使用してください。 SSR を使用していない場合は、あるユーザーのデータを別の人に誤って公開してしまうリスクはありません。しかし、それでも `load` 関数の中で副作用を持つべきではありません — 副作用がなければ、あなたのアプリケーションはより理解がしやすいものになります。 -## context と共に store を使う +## context と共に state と store を使う -独自の store が使用できないのであれば、どうやって `$page.data` や他の [app stores]($app-stores) を使用できるようにしているのだろう、と思うかもしれません。その答えは、サーバーの app stores は Svelte の [context API](/tutorial/svelte/context-api) を使用しているから、です — store は `setContext` でコンポーネントツリーにアタッチされ、subscribe するときは `getContext` で取得します。同じことを独自の store でも行うことができます: +グローバルな state が使用できないのであれば、どうやって `page.data` や他の [app state]($app-state) (や [app stores]($app-stores)) を使用できるようにしているのだろう、と思うかもしれません。その答えは、サーバーの app state や app stores は Svelte の [context API](/tutorial/svelte/context-api) を使用しているから、です — state (や store) は `setContext` でコンポーネントツリーにアタッチされ、subscribe するときは `getContext` で取得します。同じことを独自の state でも行うことができます: ```svelte ``` @@ -113,10 +108,15 @@ SSR を使用していない場合は、あるユーザーのデータを別の const user = getContext('user'); -

Welcome {$user.name}

+

Welcome {user().name}

``` -SSR でページがレンダリングされる場合、階層が深いページやコンポーネントで context ベースの store の値が更新されても、その親のコンポーネントの値には影響しません。更新されるときにはすでにレンダリング済みだからです。それとは対照的に、クライアントでは (CSR が有効な場合、これがデフォルトです)、値は伝搬し、階層の上位にあるコンポーネントやページ、レイアウトに値が反映されます。従って、ハイドレーション中の state の更新による値の 'ちらつき(flashing)' を避けるため、通常は state を上から下にコンポーネントに渡すことを推奨します。 +> [!NOTE] We're passing a function into `setContext` to keep reactivity across boundaries. Read more about it [here](/docs/svelte/$state#Passing-state-into-functions) + +> [!LEGACY] +> You also use stores from `svelte/store` for this, but when using Svelte 5 it is recommended to make use of universal reactivity instead. + +SSR でページがレンダリングされる場合、階層が深いページやコンポーネントで context ベースの state の値が更新されても、その親のコンポーネントの値には影響しません。なぜなら、その state の値が更新されるときには、親のコンポーネントはすでにレンダリング済みだからです。それとは対照的に、クライアントでは (CSR が有効な場合(デフォルトでは有効))、値は伝搬し、階層の上位にあるコンポーネントやページ、レイアウトに値が反映されます。従って、ハイドレーション中の state の更新による値の 'ちらつき(flashing)' を避けるため、通常は state を上から下にコンポーネントに渡すことを推奨します。 SSR を使用していない場合 (そして将来的にも SSR を使用する必要がないという保証がある場合) は、context API を使用しなくても、共有されるモジュールの中で state を安全に保持することができます。 @@ -127,7 +127,7 @@ SSR を使用していない場合 (そして将来的にも SSR を使用する ```svelte ``` @@ -163,14 +163,18 @@ SSR を使用していない場合 (そして将来的にも SSR を使用する このようにコンポーネントを再利用すると、サイドバースクロールの state などが保持され、変化する値の間で簡単にアニメーションを行うことができます。ナビゲーション時にコンポーネントを完全に破棄して再マウントする必要がある場合には、このパターンを使用できます: ```svelte -{#key $page.url.pathname} + + +{#key page.url.pathname} {/key} ``` ## state を URL に保存する -もし、テーブルのフィルターやソートルールなどのように、リロード後も保持されるべき state、または SSR に影響を与える state がある場合、URL search パラメータ (例: `?sort=price&order=ascending`) はこれらを置くのに適した場所です。これらは `
` や `
` の属性に置いたり、`goto('?key=value')` を使用してプログラム的に設定することもできます。`load` 関数の中では `url` パラメータを使用してアクセスでき、コンポーネントの中では `$page.url.searchParams` でアクセスできます。 +もし、テーブルのフィルターやソートルールなどのように、リロード後も保持されるべき state、または SSR に影響を与える state がある場合、URL search パラメータ (例: `?sort=price&order=ascending`) はこれらを置くのに適した場所です。これらは `` や `` の属性に置いたり、`goto('?key=value')` を使用してプログラム的に設定することもできます。`load` 関数の中では `url` パラメータを使用してアクセスでき、コンポーネントの中では `page.url.searchParams` でアクセスできます。 ## 一時的な state は snapshots に保存する diff --git a/apps/svelte.dev/content/docs/kit/20-core-concepts/index.md b/apps/svelte.dev/content/docs/kit/20-core-concepts/index.md index 46f1e3708c..2e9bc14720 100644 --- a/apps/svelte.dev/content/docs/kit/20-core-concepts/index.md +++ b/apps/svelte.dev/content/docs/kit/20-core-concepts/index.md @@ -1,3 +1,4 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Core concepts --- diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/10-building-your-app.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/10-building-your-app.md index d942dae965..b09a886054 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/10-building-your-app.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/10-building-your-app.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: アプリをビルドする --- diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/20-adapters.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/20-adapters.md index 2268e030af..279d35870d 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/20-adapters.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/20-adapters.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Adapters --- diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/30-adapter-auto.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/30-adapter-auto.md index 21a9def755..8662428960 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/30-adapter-auto.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/30-adapter-auto.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: ゼロコンフィグデプロイ --- diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/40-adapter-node.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/40-adapter-node.md index 316929e3ae..fd6efd6325 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/40-adapter-node.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/40-adapter-node.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Node サーバー --- diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/50-adapter-static.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/50-adapter-static.md index f80fb72c82..b1f37957e9 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/50-adapter-static.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/50-adapter-static.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Static site generation --- diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/55-single-page-apps.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/55-single-page-apps.md index e6757aa3e2..7c96cfa807 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/55-single-page-apps.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/55-single-page-apps.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Single-page apps --- diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/60-adapter-cloudflare.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/60-adapter-cloudflare.md index fa060eff81..99816eb4f0 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/60-adapter-cloudflare.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/60-adapter-cloudflare.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Cloudflare Pages --- @@ -82,10 +83,12 @@ export async function POST({ request, platform }) { > [!NOTE] 環境変数については、SvelteKit のビルトインの `$env` モジュールを優先的に使用したほうが良いでしょう。 -バインディングの型宣言を含めるには、、`src/app.d.ts` でこれらを参照します: +これらの型をアプリで使用できるようにするには、`@cloudflare/workers-types` をインストールし、`src/app.d.ts` でこれらを参照します: -```dts +```ts /// file: src/app.d.ts ++++import { KVNamespace, DurableObjectNamespace } from '@cloudflare/workers-types';+++ + declare global { namespace App { interface Platform { @@ -118,7 +121,7 @@ Cloudflare Pages 固有の `_headers` ファイルと `_redirects` ファイル ### 外部の資料 -[Cloudflare の、SvelteKit サイトのデプロイに関するドキュメント](https://developers.cloudflare.com/pages/framework-guides/deploy-a-svelte-site)をご参照ください。 +[Cloudflare の、SvelteKit サイトのデプロイに関するドキュメント](https://developers.cloudflare.com/pages/framework-guides/deploy-a-svelte-kit-site)をご参照ください。 ### ファイルシステムにアクセスする diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/70-adapter-cloudflare-workers.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/70-adapter-cloudflare-workers.md index 8a400a727c..2aa31fe1db 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/70-adapter-cloudflare-workers.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/70-adapter-cloudflare-workers.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Cloudflare Workers --- @@ -34,7 +35,7 @@ export default { ### config -Path to your custom `wrangler.toml` config file. +Path to your custom `wrangler.toml` or `wrangler.json` config file. ### platformProxy @@ -42,7 +43,7 @@ Preferences for the emulated `platform.env` local bindings. See the [getPlatform ## 基本設定 -この adapter では、プロジェクトの root に [wrangler.toml](https://developers.cloudflare.com/workers/platform/sites/configuration) ファイルを置くことを想定しています。内容としては以下のようなものです: +この adapter では、プロジェクトの root に [wrangler.toml/wrangler.json](https://developers.cloudflare.com/workers/platform/sites/configuration) ファイルを置くことを想定しています。内容としては以下のようなものです: ```toml /// file: wrangler.toml @@ -103,10 +104,12 @@ export async function POST({ request, platform }) { > [!NOTE] 環境変数については、SvelteKit の組み込みの `$env` モジュールの使用を推奨します。 -バインディングの型宣言を含めるには、、`src/app.d.ts` でこれらを参照します: +これらの型をアプリで使用できるようにするには、`@cloudflare/workers-types` をインストールし、`src/app.d.ts` でこれらを参照します: -```dts +```ts /// file: src/app.d.ts ++++import { KVNamespace, DurableObjectNamespace } from '@cloudflare/workers-types';+++ + declare global { namespace App { interface Platform { diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/80-adapter-netlify.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/80-adapter-netlify.md index 082ed085fe..095cfe44b5 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/80-adapter-netlify.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/80-adapter-netlify.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Netlify --- @@ -113,6 +114,6 @@ export const load = async (event) => { edge デプロイメントでは `fs` を使用することはできません。 -serverless デプロイメントでは `fs` を使用できますが、ファイルがプロジェクトからデプロイメントにコピーされないため、期待通りには動作しないでしょう。代わりに `$app/server` の `read` 関数を使用してファイルにアクセスしてください。edge デプロイメントでは `read` は動作しません(将来的に変更される可能性があります)。 +serverless デプロイメントでは `fs` を使用できますが、ファイルがプロジェクトからデプロイメントにコピーされないため、期待通りには動作しないでしょう。代わりに `$app/server` の [`read`]($app-server#read) 関数を使用してファイルにアクセスしてください。edge デプロイメントでは `read` は動作しません(将来的に変更される可能性があります)。 その代わりに、`fs` を使用する必要があるルート(route)については[プリレンダリング](page-options#prerender)する必要があります。 diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/90-adapter-vercel.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/90-adapter-vercel.md index b4b87a2a4e..d3ce0fa540 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/90-adapter-vercel.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/90-adapter-vercel.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Vercel --- @@ -44,13 +45,13 @@ export const config = { /// file: admin/+layout.js /** @type {import('@sveltejs/adapter-vercel').Config} */ export const config = { - runtime: 'nodejs18.x' + runtime: 'nodejs22.x' }; ``` 以下のオプションはすべての function に適用されます: -- `runtime`: `'edge'`、`'nodejs18.x'`、`'nodejs20.x'`。デフォルトでは、adapter はプロジェクトの Node のバージョンに対応した `'nodejs.x'` を選択します。プロジェクトの Node バージョンは Vercel のダッシュボードから設定することができます。 +- `runtime`: `'edge'`、`'nodejs18.x'`、`'nodejs20.x'`、`'nodejs22.x'`。デフォルトでは、adapter はプロジェクトの Node のバージョンに対応した `'nodejs.x'` を選択します。プロジェクトの Node バージョンは Vercel のダッシュボードから設定することができます。 - `regions`: [edge network regions](https://vercel.com/docs/concepts/edge-network/regions) の配列 (serverless functions のデフォルトは `["iad1"]`) か、`runtime` が `edge` (デフォルト) の場合は `'all'` です。serverless functions の場合の複数の regions のサポートは Enterprise Plan のみです。 - `split`: `true` の場合、ルート(route)は個別の function としてデプロイされます。`split` を adapter レベルで `true` にする場合、すべてのルート(route)が個別の function としてデプロイされます。 @@ -91,6 +92,8 @@ export default { Vercel は [Incremental Static Regeneration](https://vercel.com/docs/incremental-static-regeneration) (ISR) をサポートしており、これにより、プリレンダリングコンテンツが持つパフォーマンスとコストの利点と、ダイナミックレンダリングコンテンツが持つ柔軟性の両方を提供することができます。 +> Use ISR only on routes where every visitor should see the same content (much like when you prerender). If there's anything user-specific happening (like session cookies), they should happen on the client via JavaScript only to not leak sensitive information across visits + ISR をルート(route)に追加するには、`config` オブジェクトに `isr` プロパティを含めます: ```js @@ -99,24 +102,44 @@ import { BYPASS_TOKEN } from '$env/static/private'; export const config = { isr: { - // キャッシュされたアセットが Serverless Function を呼び出して再生成されるまでの有効期限 (秒単位)。 - // 値に `false` を設定すると、無期限になります。 expiration: 60, - - // URL で提供されるランダムな token で、アセットへのリクエストに - // __prerender_bypass= cookie を用いることで、アセットのキャッシュされたバージョンを回避することができます。 - // - // `GET` や `HEAD` リクエストに `x-prerender-revalidate: ` を付けると、アセットの再バリデート(re-validated)を強制することができます。 bypassToken: BYPASS_TOKEN, - - // 有効なクエリパラメータのリストです。他のパラメータ (例えば utm tracking codes) は無視され、 - // コンテンツが不必要に再生成されないようにします allowQuery: ['search'] } }; ``` -`expiration` プロパティは必須で、その他は任意です。 +> Using ISR on a route with `export const prerender = true` will have no effect, since the route is prerendered at build time + +The `expiration` property is required; all others are optional. The properties are discussed in more detail below. + +### expiration + +The expiration time (in seconds) before the cached asset will be re-generated by invoking the Serverless Function. Setting the value to `false` means it will never expire. In that case, you likely want to define a bypass token to re-generate on demand. + +### bypassToken + +A random token that can be provided in the URL to bypass the cached version of the asset, by requesting the asset with a `__prerender_bypass=` cookie. + +Making a `GET` or `HEAD` request with `x-prerender-revalidate: ` will force the asset to be re-validated. + +Note that the `BYPASS_TOKEN` string must be at least 32 characters long. You could generate one using the JavaScript console like so: + +```console +btoa(Math.random().toString()).substring(0,32); +``` + +Set this string as an environment variable on Vercel by logging in and going to your project then Settings > Environment Variables. For "Key" put `BYPASS_TOKEN` and for "value" use the string generated above, then hit "Save". + +To get this key known about for local development, you can use the [Vercel CLI](https://vercel.com/docs/cli/env) by running the `vercel env pull` command locally like so: + +```console +$ vercel env pull .env.development.local +``` + +### allowQuery + +A list of valid query parameters that contribute to the cache key. Other parameters (such as utm tracking codes) will be ignored, ensuring that they do not result in content being re-generated unnecessarily. By default, query parameters are ignored. > Pages that are [prerendered](page-options#prerender) will ignore ISR configuration. @@ -140,7 +163,7 @@ export function load() { ```svelte @@ -173,6 +196,6 @@ Cookie-based skew protection comes with one caveat: if a user has multiple versi edge functions では `fs` を使用することはできません。 -serverless functions では `fs` を使用できますが、ファイルがプロジェクトからデプロイメントにコピーされないため、期待通りには動作しないでしょう。代わりに `$app/server` の `read` 関数を使用してファイルにアクセスしてください。edge functions にデプロイされたルート(route)では `read` は動作しません(将来的に変更される可能性があります)。 +serverless functions では `fs` を使用できますが、ファイルがプロジェクトからデプロイメントにコピーされないため、期待通りには動作しないでしょう。代わりに `$app/server` の [`read`]($app-server#read) 関数を使用してファイルにアクセスしてください。edge functions にデプロイされたルート(route)では `read` は動作しません(将来的に変更される可能性があります)。 その代わりに、`fs` を使用する必要があるルート(route)については[プリレンダリング](page-options#prerender)する必要があります。 diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/99-writing-adapters.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/99-writing-adapters.md index 859b65552a..4a33e3e710 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/99-writing-adapters.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/99-writing-adapters.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: adapter を書く --- diff --git a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/index.md b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/index.md index 2c342fe660..1d249a2bd2 100644 --- a/apps/svelte.dev/content/docs/kit/25-build-and-deploy/index.md +++ b/apps/svelte.dev/content/docs/kit/25-build-and-deploy/index.md @@ -1,3 +1,4 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Build and deploy --- diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/10-advanced-routing.md b/apps/svelte.dev/content/docs/kit/30-advanced/10-advanced-routing.md index 31f903e71c..dc280f409d 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/10-advanced-routing.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/10-advanced-routing.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: 高度なルーティング --- diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/20-hooks.md b/apps/svelte.dev/content/docs/kit/30-advanced/20-hooks.md index 47f77ead51..8d8aadcf62 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/20-hooks.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/20-hooks.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Hooks --- @@ -39,6 +40,8 @@ export async function handle({ event, resolve }) { 未実装の場合、デフォルトは `({ event, resolve }) => resolve(event)` となります。 +During prerendering, SvelteKit crawls your pages for links and renders each route it finds. Rendering the route invokes the `handle` function (and all other route dependencies, like `load`). If you need to exclude some code from running during this phase, check that the app is not [`building`]($app-environment#building) beforehand. + ### locals カスタムデータをリクエストに追加し、`+server.js` のハンドラや server `load` 関数に渡すには、以下のように `event.locals` オブジェクトに埋め込んでください。 @@ -237,6 +240,25 @@ export async function handleError({ error, event, status, message }) { > [!NOTE] `handleError` 自体が決してエラーをスローしないようにしてください。 +### init + +This function runs once, when the server is created or the app starts in the browser, and is a useful place to do asynchronous work such as initializing a database connection. + +> [!NOTE] If your environment supports top-level await, the `init` function is really no different from writing your initialisation logic at the top level of the module, but some environments — most notably, Safari — don't. + +```js +/// file: src/hooks.server.js +import * as db from '$lib/server/database'; + +/** @type {import('@sveltejs/kit').ServerInit} */ +export async function init() { + await db.connect(); +} +``` + +> [!NOTE] +> In the browser, asynchronous work in `init` will delay hydration, so be mindful of what you put in there. + ## Universal hooks 以下は `src/hooks.js` に追加することができます。universal hooks はサーバーとクライアントの両方で実行されます (shared hooks と混同しないようにしてください、shared hooks は環境依存です)。 @@ -271,6 +293,23 @@ export function reroute({ url }) { `reroute` を使用してもブラウザのアドレスバーの内容や `event.url` の値は変更されません。 +### transport + +This is a collection of _transporters_, which allow you to pass custom types — returned from `load` and form actions — across the server/client boundary. Each transporter contains an `encode` function, which encodes values on the server (or returns `false` for anything that isn't an instance of the type) and a corresponding `decode` function: + +```js +/// file: src/hooks.js +import { Vector } from '$lib/math'; + +/** @type {import('@sveltejs/kit').Transport} */ +export const transport = { + Vector: { + encode: (value) => value instanceof Vector && [value.x, value.y], + decode: ([x, y]) => new Vector(x, y) + } +}; +``` + ## その他の参考資料 diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/25-errors.md b/apps/svelte.dev/content/docs/kit/30-advanced/25-errors.md index 6979c77c0a..d69ac6eb2d 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/25-errors.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/25-errors.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Errors --- @@ -40,22 +41,24 @@ export async function load({ params }) { } ``` -これは SvelteKit が catch する例外をスローし、それによってレスポンスのステータスコードを 404 に設定し、[`+error.svelte`](routing#error) コンポーネントをレンダリングします。`$page.error` は `error(...)` に第二引数として渡されたオブジェクトです。 +これは SvelteKit が catch する例外をスローし、それによってレスポンスのステータスコードを 404 に設定し、[`+error.svelte`](routing#error) コンポーネントをレンダリングします。`page.error` は `error(...)` に第二引数として渡されたオブジェクトです。 ```svelte -

{$page.error.message}

+

{page.error.message}

``` +> [!LEGACY] +> `$app/state` was added in SvelteKit 2.12. If you're using an earlier version or are using Svelte 4, use `$app/stores` instead. + 必要に応じて、エラーオブジェクトにプロパティを追加することができます… ```js -import { error } from '@sveltejs/kit'; - +// @filename: ambient.d.ts declare global { namespace App { interface Error { @@ -64,7 +67,10 @@ declare global { } } } +export {} +// @filename: index.js +import { error } from '@sveltejs/kit'; // ---cut--- error(404, { message: 'Not found', @@ -126,7 +132,7 @@ SvelteKit が `%sveltekit.status%` と `%sveltekit.error.message%` を、それ もし TypeScript を使用していてエラーの形式をカスタマイズする必要がある場合、アプリで `App.Error` インターフェイスを宣言することでそれができます (慣習ではこれを `src/app.d.ts` に書きますが、TypeScript が '参照' することができればどこでも構いません): -```dts +```ts /// file: src/app.d.ts declare global { namespace App { diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/30-link-options.md b/apps/svelte.dev/content/docs/kit/30-advanced/30-link-options.md index 2d3ff80b2a..58546a90fd 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/30-link-options.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/30-link-options.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Link options --- diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/40-service-workers.md b/apps/svelte.dev/content/docs/kit/30-advanced/40-service-workers.md index de52aa9cbb..44858a1e56 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/40-service-workers.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/40-service-workers.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Service workers --- diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/50-server-only-modules.md b/apps/svelte.dev/content/docs/kit/30-advanced/50-server-only-modules.md index a02311343f..621fbe081c 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/50-server-only-modules.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/50-server-only-modules.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Server-only modules --- @@ -10,7 +11,7 @@ title: Server-only modules ## Server-only utilities -The [`$app/server`]($app-server) module, which contains a `read` function for reading assets from the filesystem, can likewise only be imported by code that runs on the server. +The [`$app/server`]($app-server) module, which contains a [`read`]($app-server#read) function for reading assets from the filesystem, can likewise only be imported by code that runs on the server. ## Your modules diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/65-snapshots.md b/apps/svelte.dev/content/docs/kit/30-advanced/65-snapshots.md index 35361375c7..4b37fcb790 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/65-snapshots.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/65-snapshots.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Snapshots --- diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/67-shallow-routing.md b/apps/svelte.dev/content/docs/kit/30-advanced/67-shallow-routing.md index f10edd0ad5..c7e2cae59f 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/67-shallow-routing.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/67-shallow-routing.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Shallow routing --- @@ -12,7 +13,7 @@ SvelteKit makes this possible with the [`pushState`]($app-navigation#pushState) -{#if $page.state.showModal} +{#if page.state.showModal} history.back()} /> {/if} ``` -The modal can be dismissed by navigating back (unsetting `$page.state.showModal`) or by interacting with it in a way that causes the `close` callback to run, which will navigate back programmatically. +The modal can be dismissed by navigating back (unsetting `page.state.showModal`) or by interacting with it in a way that causes the `close` callback to run, which will navigate back programmatically. ## API The first argument to `pushState` is the URL, relative to the current URL. To stay on the current URL, use `''`. -The second argument is the new page state, which can be accessed via the [page store]($app-stores#page) as `$page.state`. You can make page state type-safe by declaring an [`App.PageState`](types#PageState) interface (usually in `src/app.d.ts`). +The second argument is the new page state, which can be accessed via the [page object]($app-state#page) as `page.state`. You can make page state type-safe by declaring an [`App.PageState`](types#PageState) interface (usually in `src/app.d.ts`). To set page state without creating a new history entry, use `replaceState` instead of `pushState`. +> [!LEGACY] +> `page.state` from `$app/state` was added in SvelteKit 2.12. If you're using an earlier version or are using Svelte 4, use `$page.state` from `$app/stores` instead. + ## Loading data for a route When shallow routing, you may want to render another `+page.svelte` inside the current page. For example, clicking on a photo thumbnail could pop up the detail view without navigating to the photo page. @@ -47,7 +51,7 @@ For this to work, you need to load the data that the `+page.svelte` expects. A c + +---{$page.data}--- ++++{page.data}+++ +``` + +Use `npx sv migrate app-state` to auto-migrate most of your `$app/stores` usages inside `.svelte` components. diff --git a/apps/svelte.dev/content/docs/kit/60-appendix/40-migrating.md b/apps/svelte.dev/content/docs/kit/60-appendix/40-migrating.md index f9eff48177..060d2cc7ed 100644 --- a/apps/svelte.dev/content/docs/kit/60-appendix/40-migrating.md +++ b/apps/svelte.dev/content/docs/kit/60-appendix/40-migrating.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Sapper からの移行 rank: 1 --- @@ -114,7 +115,7 @@ const { preloading, page, session } = stores(); `page` と `session` ストアはまだ存在しています。`preloading` は、`from` プロパティと `to` プロパティを含む `navigating` ストアに置き換えられました。`page` は `url`、`params` を持つようになりましたが、`path` と `query` はありません。 -SvelteKit では、それらにアクセスする方法が異なります。`stores` は `getStores` になりましたが、[`$app/stores`]($app-stores) から直接 `navigating`、`page`、`session` をインポートできるので、ほとんどの場合は必要ありません。 +SvelteKit では、それらにアクセスする方法が異なります。`stores` は `getStores` になりましたが、[`$app/stores`]($app-stores) から直接 `navigating`、`page`、`session` をインポートできるので、ほとんどの場合は必要ありません。もしあなたが Svelte 5 と SvelteKit 2.12 以上をお使いなら、代わりに [`$app/state`]($app-state) の使用を検討してみてください。 ### ルーティング @@ -122,7 +123,7 @@ SvelteKit では、それらにアクセスする方法が異なります。`sto ### Segments -以前までは、レイアウトコンポーネントは子のセグメントを表す `segment` プロパティを受け取っていましたが、この機能は削除されました。より柔軟な `$page.url.pathname` の値を使用し、お望みのセグメントを取得してください。 +以前までは、レイアウトコンポーネントは子のセグメントを表す `segment` プロパティを受け取っていましたが、この機能は削除されました。より柔軟な `$page.url.pathname` (や `page.url.pathname`) の値を使用し、お望みのセグメントを取得してください。 ### URLs diff --git a/apps/svelte.dev/content/docs/kit/60-appendix/50-additional-resources.md b/apps/svelte.dev/content/docs/kit/60-appendix/50-additional-resources.md index 591b65d0e8..bc98756eb5 100644 --- a/apps/svelte.dev/content/docs/kit/60-appendix/50-additional-resources.md +++ b/apps/svelte.dev/content/docs/kit/60-appendix/50-additional-resources.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Additional resources --- @@ -20,6 +21,6 @@ title: Additional resources ## サポート -[Discord](https://svelte.dev/chat) や [StackOverflow](https://stackoverflow.com/questions/tagged/sveltekit) でヘルプを求めることができます。他の方の時間を尊重するため、まずは FAQ、Googleまたは他の検索エンジン、issue tracker、Discord のチャット履歴などから、問題に関連する情報を検索してください。回答する方より質問する方のほうが多いので、こうすることでコミュニティをスケーラブルに発展させることができると思います。 +[Discord](/chat) や [StackOverflow](https://stackoverflow.com/questions/tagged/sveltekit) でヘルプを求めることができます。他の方の時間を尊重するため、まずは FAQ、Googleまたは他の検索エンジン、issue tracker、Discord のチャット履歴などから、問題に関連する情報を検索してください。回答する方より質問する方のほうが多いので、こうすることでコミュニティをスケーラブルに発展させることができると思います。 -> 日本語翻訳版 追記:上記のDiscordはSvelte本体のもので、英語でコミュニケーションが行われています。もし日本語で質問したり交流したいのであれば、[Svelte日本のDiscord](https://discord.com/invite/YTXq3ZtBbx)にどうぞ! \ No newline at end of file +> 日本語翻訳版 追記:上記のDiscordはSvelte本体のもので、英語でコミュニケーションが行われています。もし日本語で質問したり交流したいのであれば、[Svelte日本のDiscord](https://discord.com/invite/YTXq3ZtBbx)にどうぞ! diff --git a/apps/svelte.dev/content/docs/kit/60-appendix/60-glossary.md b/apps/svelte.dev/content/docs/kit/60-appendix/60-glossary.md index fd2ddcd9b9..200789ce35 100644 --- a/apps/svelte.dev/content/docs/kit/60-appendix/60-glossary.md +++ b/apps/svelte.dev/content/docs/kit/60-appendix/60-glossary.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Glossary --- diff --git a/apps/svelte.dev/content/docs/kit/60-appendix/index.md b/apps/svelte.dev/content/docs/kit/60-appendix/index.md index a8e02800ad..80bf00f099 100644 --- a/apps/svelte.dev/content/docs/kit/60-appendix/index.md +++ b/apps/svelte.dev/content/docs/kit/60-appendix/index.md @@ -1,3 +1,4 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Appendix --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md b/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md index 0eb8a5b8c6..b3c855540f 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/10-@sveltejs-kit.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: @sveltejs/kit --- @@ -7,6 +8,7 @@ title: @sveltejs/kit ```js // @noErrors import { + Server, VERSION, error, fail, @@ -19,6 +21,43 @@ import { } from '@sveltejs/kit'; ``` +## Server + +
+ +```dts +class Server {/*…*/} +``` + +
+ +```dts +constructor(manifest: SSRManifest); +``` + +
+
+ +
+ +```dts +init(options: ServerInitOptions): Promise; +``` + +
+
+ +
+ +```dts +respond(request: Request, options: RequestOptions): Promise; +``` + +
+
+ + + ## VERSION
@@ -94,9 +133,7 @@ Checks whether this is an action failure thrown by `fail`.
```dts -function isActionFailure( - e: unknown -): e is ActionFailure; +function isActionFailure(e: unknown): e is ActionFailure; ```
@@ -158,6 +195,13 @@ function json( Redirect a request. When called during request handling, SvelteKit will return a redirect response. Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it. +Most common status codes: + * `303 See Other`: redirect as a GET request (often used after a form POST request) + * `307 Temporary Redirect`: redirect will keep the request method + * `308 Permanent Redirect`: redirect will keep the request method, SEO will be transferred to the new page + +[See all redirect status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages) +
```dts @@ -337,7 +381,7 @@ The name of the adapter, using for logging. Will typically correspond to the pac
```dts -adapt(builder: Builder): MaybePromise; +adapt: (builder: Builder) => MaybePromise; ```
@@ -388,7 +432,7 @@ Test support for `read` from `$app/server`
```dts -emulate?(): MaybePromise; +emulate?: () => MaybePromise; ```
@@ -471,7 +515,7 @@ interface BeforeNavigate extends Navigation {/*…*/}
```dts -cancel(): void; +cancel: () => void; ```
@@ -508,7 +552,7 @@ Print messages to the console. `log.info` and `log.minor` are silent unless Vite
```dts -rimraf(dir: string): void; +rimraf: (dir: string) => void; ```
@@ -521,7 +565,7 @@ Remove `dir` and all its contents.
```dts -mkdirp(dir: string): void; +mkdirp: (dir: string) => void; ```
@@ -573,7 +617,7 @@ An array of all routes (including prerendered)
```dts -createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise; +createEntries: (fn: (route: RouteDefinition) => AdapterEntry) => Promise; ```
@@ -593,7 +637,7 @@ Create separate functions that map to one or more routes of your app.
```dts -findServerAssets(routes: RouteDefinition[]): string[]; +findServerAssets: (routes: RouteDefinition[]) => string[]; ```
@@ -606,7 +650,7 @@ Find all the assets imported by server files belonging to `routes`
```dts -generateFallback(dest: string): Promise; +generateFallback: (dest: string) => Promise; ```
@@ -619,7 +663,7 @@ Generate a fallback page for a static webserver to use when no route is matched.
```dts -generateEnvModule(): void; +generateEnvModule: () => void; ```
@@ -632,7 +676,7 @@ Generate a module exposing build-time environment variables as `$env/dynamic/pub
```dts -generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string; +generateManifest: (opts: { relativePath: string; routes?: RouteDefinition[] }) => string; ```
@@ -643,7 +687,7 @@ generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): st
-Generate a server-side manifest to initialise the SvelteKit [server](https://svelte.dev/docs/kit/@sveltejs-kit#Server) with. +Generate a server-side manifest to initialise the SvelteKit [server](/docs/kit/@sveltejs-kit#Server) with.
@@ -651,7 +695,7 @@ Generate a server-side manifest to initialise the SvelteKit [server](https://sve
```dts -getBuildDirectory(name: string): string; +getBuildDirectory: (name: string) => string; ```
@@ -670,7 +714,7 @@ Resolve a path to the `name` directory inside `outDir`, e.g. `/path/to/.svelte-k
```dts -getClientDirectory(): string; +getClientDirectory: () => string; ```
@@ -683,7 +727,7 @@ Get the fully resolved path to the directory containing client-side assets, incl
```dts -getServerDirectory(): string; +getServerDirectory: () => string; ```
@@ -696,7 +740,7 @@ Get the fully resolved path to the directory containing server-side code.
```dts -getAppPath(): string; +getAppPath: () => string; ```
@@ -709,7 +753,7 @@ Get the application path including any configured `base` path, e.g. `my-base-pat
```dts -writeClient(dest: string): string[]; +writeClient: (dest: string) => string[]; ```
@@ -729,7 +773,7 @@ Write client assets to `dest`.
```dts -writePrerendered(dest: string): string[]; +writePrerendered: (dest: string) => string[]; ```
@@ -749,7 +793,7 @@ Write prerendered files to `dest`.
```dts -writeServer(dest: string): string[]; +writeServer: (dest: string) => string[]; ```
@@ -769,14 +813,14 @@ Write server-side code to `dest`.
```dts -copy( +copy: ( from: string, to: string, opts?: { filter?(basename: string): boolean; replace?: Record; } -): string[]; +) => string[]; ```
@@ -799,7 +843,7 @@ Copy a file or directory.
```dts -compress(directory: string): Promise; +compress: (directory: string) => Promise; ```
@@ -815,6 +859,24 @@ Compress files in `directory` with gzip and brotli, where appropriate. Generates
+## ClientInit + +
+ +Available since 2.10.0 + +
+ +The [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked once the app starts in the browser + +
+ +```dts +type ClientInit = () => MaybePromise; +``` + +
+ ## Config See the [configuration reference](/docs/kit/configuration) for details. @@ -830,7 +892,7 @@ interface Cookies {/*…*/}
```dts -get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined; +get: (name: string, opts?: import('cookie').CookieParseOptions) => string | undefined; ```
@@ -850,7 +912,7 @@ Gets a cookie that was previously set with `cookies.set`, or from the request he
```dts -getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>; +getAll: (opts?: import('cookie').CookieParseOptions) => Array<{ name: string; value: string }>; ```
@@ -869,11 +931,11 @@ Gets all cookies that were previously set with `cookies.set`, or from the reques
```dts -set( +set: ( name: string, value: string, opts: import('cookie').CookieSerializeOptions & { path: string } -): void; +) => void; ```
@@ -898,7 +960,7 @@ You must specify a `path` for the cookie. In most cases you should explicitly se
```dts -delete(name: string, opts: import('cookie').CookieSerializeOptions & { path: string }): void; +delete: (name: string, opts: import('cookie').CookieSerializeOptions & { path: string }) => void; ```
@@ -920,11 +982,11 @@ You must specify a `path` for the cookie. In most cases you should explicitly se
```dts -serialize( +serialize: ( name: string, value: string, opts: import('cookie').CookieSerializeOptions & { path: string } -): string; +) => string; ```
@@ -982,10 +1044,10 @@ This allows you to modify response headers or bodies, or bypass SvelteKit entire ```dts type Handle = (input: { event: RequestEvent; - resolve( + resolve: ( event: RequestEvent, opts?: ResolveOptions - ): MaybePromise; + ) => MaybePromise; }) => MaybePromise; ``` @@ -1171,10 +1233,10 @@ fetch: typeof fetch; - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. -- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://svelte.dev/docs/kit/hooks#Server-hooks-handle) +- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](/docs/kit/hooks#Server-hooks-handle) - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. -You can learn more about making credentialed requests with cookies [here](https://svelte.dev/docs/kit/load#Cookies) +You can learn more about making credentialed requests with cookies [here](/docs/kit/load#Cookies)
@@ -1195,7 +1257,7 @@ Contains the data returned by the route's server `load` function (in `+layout.se
```dts -setHeaders(headers: Record): void; +setHeaders: (headers: Record) => void; ```
@@ -1220,7 +1282,7 @@ export async function load({ fetch, setHeaders }) { Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. -You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://svelte.dev/docs/kit/@sveltejs-kit#Cookies) API in a server-only `load` function instead. +You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](/docs/kit/@sveltejs-kit#Cookies) API in a server-only `load` function instead. `setHeaders` has no effect when a `load` function runs in the browser. @@ -1230,7 +1292,7 @@ You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](h
```dts -parent(): Promise; +parent: () => Promise; ```
@@ -1246,12 +1308,12 @@ Be careful not to introduce accidental waterfalls when using `await parent()`. I
```dts -depends(...deps: Array<`${string}:${string}`>): void; +depends: (...deps: Array<`${string}:${string}`>) => void; ```
-This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](https://svelte.dev/docs/kit/$app-navigation#invalidate) to cause `load` to rerun. +This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/kit/$app-navigation#invalidate) to cause `load` to rerun. Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. @@ -1294,7 +1356,7 @@ export async function load({ depends }) {
```dts -untrack(fn: () => T): T; +untrack: (fn: () => T) => T; ```
@@ -1616,7 +1678,7 @@ Since `onNavigate` callbacks are called immediately before a client-side navigat ## Page -The shape of the `$page` store +The shape of the [`page`](/docs/kit/$app-state#page) reactive object and the [`$page`](/docs/kit/$app-stores) store.
@@ -1638,7 +1700,7 @@ url: URL;
-The URL of the current page +The URL of the current page.
@@ -1651,7 +1713,7 @@ params: Params;
-The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object +The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
@@ -1664,7 +1726,7 @@ route: {/*…*/}
-Info about the current route +Info about the current route.
@@ -1674,7 +1736,7 @@ id: RouteId;
-The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` +The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`.
@@ -1690,7 +1752,7 @@ status: number;
-Http status code of the current page +HTTP status code of the current page.
@@ -1729,7 +1791,7 @@ state: App.PageState;
-The page state, which can be manipulated using the [`pushState`](https://svelte.dev/docs/kit/$app-navigation#pushState) and [`replaceState`](https://svelte.dev/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`. +The page state, which can be manipulated using the [`pushState`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.
@@ -1742,7 +1804,7 @@ form: any;
-Filled only after a form submission. See [form actions](https://svelte.dev/docs/kit/form-actions) for more info. +Filled only after a form submission. See [form actions](/docs/kit/form-actions) for more info.
@@ -1844,10 +1906,10 @@ fetch: typeof fetch; - It can be used to make credentialed requests on the server, as it inherits the `cookie` and `authorization` headers for the page request. - It can make relative requests on the server (ordinarily, `fetch` requires a URL with an origin when used in a server context). - Internal requests (e.g. for `+server.js` routes) go directly to the handler function when running on the server, without the overhead of an HTTP call. -- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](https://svelte.dev/docs/kit/hooks#Server-hooks-handle) +- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the `text` and `json` methods of the `Response` object. Note that headers will _not_ be serialized, unless explicitly included via [`filterSerializedResponseHeaders`](/docs/kit/hooks#Server-hooks-handle) - During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request. -You can learn more about making credentialed requests with cookies [here](https://svelte.dev/docs/kit/load#Cookies) +You can learn more about making credentialed requests with cookies [here](/docs/kit/load#Cookies)
@@ -1855,7 +1917,7 @@ You can learn more about making credentialed requests with cookies [here](https:
```dts -getClientAddress(): string; +getClientAddress: () => string; ```
@@ -1873,7 +1935,7 @@ locals: App.Locals;
-Contains custom data that was added to the request within the [`server handle hook`](https://svelte.dev/docs/kit/hooks#Server-hooks-handle). +Contains custom data that was added to the request within the [`server handle hook`](/docs/kit/hooks#Server-hooks-handle).
@@ -1946,7 +2008,7 @@ The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/b
```dts -setHeaders(headers: Record): void; +setHeaders: (headers: Record) => void; ```
@@ -1971,7 +2033,7 @@ export async function load({ fetch, setHeaders }) { Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once. -You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](https://svelte.dev/docs/kit/@sveltejs-kit#Cookies) API instead. +You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](/docs/kit/@sveltejs-kit#Cookies) API instead.
@@ -2039,6 +2101,12 @@ type RequestHandler< ## Reroute +
+ +Available since 2.3.0 + +
+ The [`reroute`](/docs/kit/hooks#Universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render.
@@ -2060,7 +2128,7 @@ interface ResolveOptions {/*…*/}
```dts -transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; +transformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise; ```
@@ -2081,7 +2149,7 @@ but they will always be split at sensible boundaries such as `%sveltekit.head%`
```dts -filterSerializedResponseHeaders?(name: string, value: string): boolean; +filterSerializedResponseHeaders?: (name: string, value: string) => boolean; ```
@@ -2102,7 +2170,7 @@ By default, none will be included.
```dts -preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; +preload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean; ```
@@ -2284,7 +2352,7 @@ routes: SSRRoute[];
```dts -matchers(): Promise>; +matchers: () => Promise>; ```
@@ -2305,41 +2373,24 @@ A `[file]: size` map of all assets imported by server code
-## Server +## ServerInit -
+
-```dts -class Server {/*…*/} -``` +Available since 2.10.0 -
+
-```dts -constructor(manifest: SSRManifest); -``` - -
-
+The [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked before the server responds to its first request -
+
```dts -init(options: ServerInitOptions): Promise; +type ServerInit = () => MaybePromise; ``` -
-
- -```dts -respond(request: Request, options: RequestOptions): Promise; -``` - -
-
- ## ServerInitOptions
@@ -2422,7 +2473,7 @@ interface ServerLoadEvent<
```dts -parent(): Promise; +parent: () => Promise; ```
@@ -2437,12 +2488,12 @@ Be careful not to introduce accidental waterfalls when using `await parent()`. I
```dts -depends(...deps: string[]): void; +depends: (...deps: string[]) => void; ```
-This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](https://svelte.dev/docs/kit/$app-navigation#invalidate) to cause `load` to rerun. +This function declares that the `load` function has a _dependency_ on one or more URLs or custom identifiers, which can subsequently be used with [`invalidate()`](/docs/kit/$app-navigation#invalidate) to cause `load` to rerun. Most of the time you won't need this, as `fetch` calls `depends` on your behalf — it's only necessary if you're using a custom API client that bypasses `fetch`. @@ -2485,7 +2536,7 @@ export async function load({ depends }) {
```dts -untrack(fn: () => T): T; +untrack: (fn: () => T) => T; ```
@@ -2552,7 +2603,7 @@ type SubmitFunction< formElement: HTMLFormElement; controller: AbortController; submitter: HTMLElement | null; - cancel(): void; + cancel: () => void; }) => MaybePromise< | void | ((opts: { @@ -2565,16 +2616,88 @@ type SubmitFunction< * @param options Set `reset: false` if you don't want the `` values to be reset after a successful submission. * @param invalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission. */ - update(options?: { + update: (options?: { reset?: boolean; invalidateAll?: boolean; - }): Promise; + }) => Promise; }) => void) >; ```
+## Transport + +
+ +Available since 2.11.0 + +
+ +The [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook allows you to transport custom types across the server/client boundary. + +Each transporter has a pair of `encode` and `decode` functions. On the server, `encode` determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or `false` otherwise). + +In the browser, `decode` turns the encoding back into an instance of the custom type. + +```ts +import type { Transport } from '@sveltejs/kit'; + +declare class MyCustomType { + data: any +} + +// hooks.js +export const transport: Transport = { + MyCustomType: { + encode: (value) => value instanceof MyCustomType && [value.data], + decode: ([data]) => new MyCustomType(data) + } +}; +``` + +
+ +```dts +type Transport = Record; +``` + +
+ +## Transporter + +A member of the [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook. + +
+ +```dts +interface Transporter< + T = any, + U = Exclude< + any, + false | 0 | '' | null | undefined | typeof NaN + > +> {/*…*/} +``` + +
+ +```dts +encode: (value: T) => false | U; +``` + +
+
+ +
+ +```dts +decode: (data: U) => T; +``` + +
+
+ ## Private types diff --git a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-hooks.md b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-hooks.md index 96a725f3b5..e92bc1eaed 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-hooks.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-hooks.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: @sveltejs/kit/hooks --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node-polyfills.md b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node-polyfills.md index a1ae80005d..523543ae5c 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node-polyfills.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node-polyfills.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: @sveltejs/kit/node/polyfills --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node.md b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node.md index 37a0ea2a28..750a9a4b9d 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-node.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: @sveltejs/kit/node --- @@ -15,6 +16,12 @@ import { ## createReadableStream +
+ +Available since 2.4.0 + +
+ Converts a file on disk to a readable stream
diff --git a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-vite.md b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-vite.md index 71ab49110e..1bbe616d49 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-vite.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/15-@sveltejs-kit-vite.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: @sveltejs/kit/vite --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-environment.md b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-environment.md index 043d8c8cb7..825f7a9669 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-environment.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-environment.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/environment --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-forms.md b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-forms.md index e024a0ba0a..e9c99d5c15 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-forms.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-forms.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/forms --- @@ -11,7 +12,7 @@ import { applyAction, deserialize, enhance } from '$app/forms'; ## applyAction -This action updates the `form` property of the current page with the given data and updates `$page.status`. +This action updates the `form` property of the current page with the given data and updates `page.status`. In case of an error, it redirects to the nearest error page.
@@ -79,12 +80,15 @@ If nothing is returned, the fallback will be used. If this function or its return value isn't set, it - falls back to updating the `form` prop with the returned data if the action is on the same page as the form -- updates `$page.status` +- updates `page.status` - resets the `` element and invalidates all data in case of successful submission with no redirect response - redirects in case of a redirect response - redirects to the nearest error page in case of an unexpected error If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback. +It accepts an options object +- `reset: false` if you don't want the `` values to be reset after a successful submission +- `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission
diff --git a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-navigation.md b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-navigation.md index eb6fae486a..ac29666d00 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-navigation.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-navigation.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/navigation --- @@ -23,7 +24,7 @@ import { ## afterNavigate -A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a new URL. +A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a URL. `afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted. @@ -43,7 +44,7 @@ function afterNavigate( ## beforeNavigate -A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. +A navigation interceptor that triggers before we navigate to a URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls. Calling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response. @@ -84,7 +85,9 @@ function disableScrollHandling(): void; ## goto +Allows you to navigate programmatically to a given route, with options such as keeping the current element focused. Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`. + For external URLs, use `window.location = url` instead of calling `goto(url)`.
@@ -98,6 +101,9 @@ function goto( noScroll?: boolean | undefined; keepFocus?: boolean | undefined; invalidateAll?: boolean | undefined; + invalidate?: + | (string | URL | ((url: URL) => boolean))[] + | undefined; state?: App.PageState | undefined; } | undefined @@ -227,7 +233,7 @@ function preloadData(href: string): Promise< ## pushState -Programmatically create a new history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](/docs/kit/shallow-routing). +Programmatically create a new history entry with the given `page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](/docs/kit/shallow-routing).
@@ -244,7 +250,7 @@ function pushState( ## replaceState -Programmatically replace the current history entry with the given `$page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](/docs/kit/shallow-routing). +Programmatically replace the current history entry with the given `page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](/docs/kit/shallow-routing).
diff --git a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-paths.md b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-paths.md index eb2416e52c..b6740cb8ea 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-paths.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-paths.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/paths --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-server.md b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-server.md index 32ba649b36..ff1d26f383 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-server.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-server.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/server --- @@ -11,6 +12,12 @@ import { read } from '$app/server'; ## read +
+ +Available since 2.4.0 + +
+ Read the contents of an imported asset from the filesystem ```js diff --git a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-state.md b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-state.md new file mode 100644 index 0000000000..652ec7ac4f --- /dev/null +++ b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-state.md @@ -0,0 +1,105 @@ +--- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts +title: $app/state +--- + +SvelteKit makes three read-only state objects available via the `$app/state` module — `page`, `navigating` and `updated`. + +> [!NOTE] +> This module was added in 2.12. If you're using an earlier version of SvelteKit, use [`$app/stores`]($app-stores) instead. + + + +```js +// @noErrors +import { navigating, page, updated } from '$app/state'; +``` + +## navigating + +A read-only object representing an in-progress navigation, with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties. +Values are `null` when no navigation is occurring, or during server rendering. + +
+ +```dts +const navigating: + | import('@sveltejs/kit').Navigation + | { + from: null; + to: null; + type: null; + willUnload: null; + delta: null; + complete: null; + }; +``` + +
+ + + +## page + +A read-only reactive object with information about the current page, serving several use cases: +- retrieving the combined `data` of all pages/layouts anywhere in your component tree (also see [loading data](/docs/kit/load)) +- retrieving the current value of the `form` prop anywhere in your component tree (also see [form actions](/docs/kit/form-actions)) +- retrieving the page state that was set through `goto`, `pushState` or `replaceState` (also see [goto](/docs/kit/$app-navigation#goto) and [shallow routing](/docs/kit/shallow-routing)) +- retrieving metadata such as the URL you're on, the current route and its parameters, and whether or not there was an error + +```svelte + + + +

Currently at {page.url.pathname}

+ +{#if page.error} + Problem detected +{:else} + All systems operational +{/if} +``` + +Changes to `page` are available exclusively with runes. (The legacy reactivity syntax will not reflect any changes) + +```svelte + + +``` + +On the server, values can only be read during rendering (in other words _not_ in e.g. `load` functions). In the browser, the values can be read at any time. + +
+ +```dts +const page: import('@sveltejs/kit').Page; +``` + +
+ + + +## updated + +A read-only reactive value that's initially `false`. If [`version.pollInterval`](/docs/kit/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update `current` to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling. + +
+ +```dts +const updated: { + get current(): boolean; + check(): Promise; +}; +``` + +
+ + + + diff --git a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-stores.md b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-stores.md index 2698387c39..c6d0cfe469 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/20-$app-stores.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/20-$app-stores.md @@ -1,7 +1,10 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $app/stores --- +This module contains store-based equivalents of the exports from [`$app/state`]($app-state). If you're using SvelteKit 2.12 or later, use that module instead. + ```js @@ -29,6 +32,12 @@ function getStores(): { ## navigating +
+ +Use `navigating` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)) + +
+ A readable store. When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties. When navigating finishes, its value reverts to `null`. @@ -49,6 +58,12 @@ const navigating: import('svelte/store').Readable< ## page +
+ +Use `page` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)) + +
+ A readable store whose value contains page data. On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. @@ -67,6 +82,12 @@ const page: import('svelte/store').Readable< ## updated +
+ +Use `updated` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)) + +
+ A readable store whose initial value is `false`. If [`version.pollInterval`](/docs/kit/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling. On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. diff --git a/apps/svelte.dev/content/docs/kit/98-reference/25-$env-dynamic-private.md b/apps/svelte.dev/content/docs/kit/98-reference/25-$env-dynamic-private.md index 8ac9dd33bb..88d57bc8a6 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/25-$env-dynamic-private.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/25-$env-dynamic-private.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $env/dynamic/private --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/25-$env-dynamic-public.md b/apps/svelte.dev/content/docs/kit/98-reference/25-$env-dynamic-public.md index 8ae6bd4d89..36118b00af 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/25-$env-dynamic-public.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/25-$env-dynamic-public.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $env/dynamic/public --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/25-$env-static-private.md b/apps/svelte.dev/content/docs/kit/98-reference/25-$env-static-private.md index 43410b8052..87b6389f27 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/25-$env-static-private.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/25-$env-static-private.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $env/static/private --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/25-$env-static-public.md b/apps/svelte.dev/content/docs/kit/98-reference/25-$env-static-public.md index 2597e6729c..e29cd387c4 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/25-$env-static-public.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/25-$env-static-public.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $env/static/public --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/26-$lib.md b/apps/svelte.dev/content/docs/kit/98-reference/26-$lib.md index d9262a2954..9b94d47138 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/26-$lib.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/26-$lib.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $lib --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/27-$service-worker.md b/apps/svelte.dev/content/docs/kit/98-reference/27-$service-worker.md index 0fe6457a17..6245eea1b7 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/27-$service-worker.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/27-$service-worker.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: $service-worker --- diff --git a/apps/svelte.dev/content/docs/kit/98-reference/50-configuration.md b/apps/svelte.dev/content/docs/kit/98-reference/50-configuration.md index 4c316a3ed0..f1302471a9 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/50-configuration.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/50-configuration.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: Configuration --- @@ -48,7 +49,7 @@ compilerOptions?: CompileOptions;
-Options passed to [`svelte.compile`](https://svelte.dev/docs/svelte/svelte-compiler#CompileOptions). +Options passed to [`svelte.compile`](/docs/svelte/svelte-compiler#CompileOptions).
@@ -138,7 +139,7 @@ The `kit` property configures SvelteKit, and can have the following properties:
-Your [adapter](https://svelte.dev/docs/kit/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms. +Your [adapter](/docs/kit/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms.
@@ -246,9 +247,9 @@ When pages are prerendered, the CSP header is added via a `` ta > [!NOTE] When `mode` is `'auto'`, SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden. -> [!NOTE] Note that most [Svelte transitions](https://svelte.dev/tutorial/svelte/transition) work by creating an inline ` +``` + ### element_invalid_self_closing_tag ``` Self-closing HTML tags for non-void elements are ambiguous — use `<%name% ...>` rather than `<%name% ... />` ``` +In HTML, there's [no such thing as a self-closing tag](https://jakearchibald.com/2023/against-self-closing-tags-in-html/). While this _looks_ like a self-contained element with some text next to it... + +```html +
+ some text! +
+``` + +...a spec-compliant HTML parser (such as a browser) will in fact parse it like this, with the text _inside_ the icon: + +```html +
+ some text! +
+``` + +Some templating languages (including Svelte) will 'fix' HTML by turning `` into ``. Others adhere to the spec. Both result in ambiguity and confusion when copy-pasting code between different contexts, and as such Svelte prompts you to resolve the ambiguity directly by having an explicit closing tag. + +To automate this, run the dedicated migration: + +```bash +npx sv migrate self-closing-tags +``` + +In a future version of Svelte, self-closing tags may be upgraded from a warning to an error. + ### event_directive_deprecated ``` Using `on:%name%` to listen to the %name% event is deprecated. Use the event attribute `on%name%` instead ``` +See [the migration guide](v5-migration-guide#Event-changes) for more info. + ### export_let_unused ``` @@ -640,15 +682,17 @@ Component has unused export property '%name%'. If it is for external reference o Svelte 5 components are no longer classes. Instantiate them using `mount` or `hydrate` (imported from 'svelte') instead. ``` +See the [migration guide](v5-migration-guide#Components-are-no-longer-classes) for more info. + ### node_invalid_placement_ssr ``` -%thing% is invalid inside `<%parent%>`. When rendering this component on the server, the resulting HTML will be modified by the browser, likely resulting in a `hydration_mismatch` warning +%message%. When rendering this component on the server, the resulting HTML will be modified by the browser (by moving, removing, or inserting elements), likely resulting in a `hydration_mismatch` warning ``` HTML restricts where certain elements can appear. In case of a violation the browser will 'repair' the HTML in a way that breaks Svelte's assumptions about the structure of your components. Some examples: -- `

hello

world

` will result in `

hello

world

` for example (the `
` autoclosed the `

` because `

` cannot contain block-level elements) +- `

hello

world

` will result in `

hello

world

` (the `
` autoclosed the `

` because `

` cannot contain block-level elements) - `

option a
` will result in `` (the `
` is removed) - `
cell
` will result in `
cell
` (a `` is auto-inserted) @@ -660,6 +704,30 @@ This code will work when the component is rendered on the client (which is why t `%name%` is updated, but is not declared with `$state(...)`. Changing its value will not correctly trigger updates ``` +This warning is thrown when the compiler detects the following: +- a variable was declared without `$state` or `$state.raw` +- the variable is reassigned +- the variable is read in a reactive context + +In this case, changing the value will not correctly trigger updates. Example: + +```svelte + + +

This value updates: {reactive}

+

This value does not update: {stale}

+ + +``` + +To fix this, wrap your variable declaration with `$state`. + ### options_deprecated_accessors ``` @@ -726,18 +794,18 @@ Reactive declarations only exist at the top level of the instance script Reassignments of module-level declarations will not cause reactive statements to update ``` -### reactive_declaration_non_reactive_property - -``` -Properties of objects and arrays are not reactive unless in runes mode. Changes to this property will not cause the reactive statement to update -``` - ### script_context_deprecated ``` `context="module"` is deprecated, use the `module` attribute instead ``` +```svelte + +``` + ### script_unknown_attribute ``` @@ -750,12 +818,79 @@ Unrecognized attribute — should be one of `generics`, `lang` or `module`. If t Using `` to render parent content is deprecated. Use `{@render ...}` tags instead ``` +See [the migration guide](v5-migration-guide#Snippets-instead-of-slots) for more info. + ### state_referenced_locally ``` State referenced in its own scope will never update. Did you mean to reference it inside a closure? ``` +This warning is thrown when the compiler detects the following: +- A reactive variable is declared +- the variable is reassigned +- the variable is referenced inside the same scope it is declared and it is a non-reactive context + +In this case, the state reassignment will not be noticed by whatever you passed it to. For example, if you pass the state to a function, that function will not notice the updates: + +```svelte + + + + +``` + +```svelte + + + + +

The count is {count}

+``` + +To fix this, reference the variable such that it is lazily evaluated. For the above example, this can be achieved by wrapping `count` in a function: + +```svelte + + + + +``` + +```svelte + + + + +

The count is {+++count()+++}

+``` + +For more info, see [Passing state into functions]($state#Passing-state-into-functions). + ### store_rune_conflict ``` @@ -811,6 +946,8 @@ A derived value may be used in other contexts: `` is deprecated — use self-imports (e.g. `import %name% from './%basename%'`) instead ``` +See [the note in the docs](legacy-svelte-self) for more info. + ### unknown_code ``` diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/.generated/server-errors.md b/apps/svelte.dev/content/docs/svelte/98-reference/.generated/server-errors.md index 8cf6727da9..c3e8b53c31 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/.generated/server-errors.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/.generated/server-errors.md @@ -5,3 +5,5 @@ ``` `%name%(...)` is not available on the server ``` + +Certain methods such as `mount` cannot be invoked while running in a server context. Avoid calling them eagerly, i.e. not during render. diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/.generated/shared-errors.md b/apps/svelte.dev/content/docs/svelte/98-reference/.generated/shared-errors.md index 52ef9d5f88..0102aafcbc 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/.generated/shared-errors.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/.generated/shared-errors.md @@ -6,12 +6,54 @@ Cannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet instead ``` +This error would be thrown in a setup like this: + +```svelte + + + {entry} + +``` + +```svelte + + + +
    + {#each items as item} +
  • {@render children(item)}
  • + {/each} +
+``` + +Here, `List.svelte` is using `{@render children(item)` which means it expects `Parent.svelte` to use snippets. Instead, `Parent.svelte` uses the deprecated `let:` directive. This combination of APIs is incompatible, hence the error. + ### lifecycle_outside_component ``` `%name%(...)` can only be used during component initialisation ``` +Certain lifecycle methods can only be used during component initialisation. To fix this, make sure you're invoking the method inside the _top level of the instance script_ of your component. + +```svelte + + + +``` + ### store_invalid_shape ``` diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/.generated/shared-warnings.md b/apps/svelte.dev/content/docs/svelte/98-reference/.generated/shared-warnings.md index e9327e1e98..f449a4031e 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/.generated/shared-warnings.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/.generated/shared-warnings.md @@ -6,6 +6,8 @@ `` is a void element — it cannot have content ``` +Elements such as `` cannot have content, any children passed to these elements will be ignored. + ### state_snapshot_uncloneable ``` @@ -17,3 +19,10 @@ The following properties cannot be cloned with `$state.snapshot` — the return %properties% ``` + +`$state.snapshot` tries to clone the given value in order to return a reference that no longer changes. Certain objects may not be cloneable, in which case the original value is returned. In the following example, `property` is cloned, but `window` is not, because DOM elements are uncloneable: + +```js +const object = $state({ property: 'this is cloneable', window }) +const snapshot = $state.snapshot(object); +``` diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md b/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md index e647351f91..1d6b62dc14 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/20-svelte.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: svelte --- @@ -7,6 +8,8 @@ title: svelte ```js // @noErrors import { + SvelteComponent, + SvelteComponentTyped, afterUpdate, beforeUpdate, createEventDispatcher, @@ -26,11 +29,153 @@ import { } from 'svelte'; ``` +## SvelteComponent + +This was the base class for Svelte components in Svelte 4. Svelte 5+ components +are completely different under the hood. For typing, use `Component` instead. +To instantiate components, use `mount` instead. +See [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info. + +
+ +```dts +class SvelteComponent< + Props extends Record = Record, + Events extends Record = any, + Slots extends Record = any +> {/*…*/} +``` + +
+ +```dts +static element?: typeof HTMLElement; +``` + +
+ +The custom element version of the component. Only present if compiled with the `customElement` compiler option + +
+
+ +
+ +```dts +[prop: string]: any; +``` + +
+
+ +
+ +```dts +constructor(options: ComponentConstructorOptions>); +``` + +
+ +
+ +- deprecated This constructor only exists when using the `asClassComponent` compatibility helper, which +is a stop-gap solution. Migrate towards using `mount` instead. See +[migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info. + +
+ +
+
+ +
+ +```dts +$destroy(): void; +``` + +
+ +
+ +- deprecated This method only exists when using one of the legacy compatibility helpers, which +is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) +for more info. + +
+ +
+
+ +
+ +```dts +$on>( + type: K, + callback: (e: Events[K]) => void +): () => void; +``` + +
+ +
+ +- deprecated This method only exists when using one of the legacy compatibility helpers, which +is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) +for more info. + +
+ +
+
+ +
+ +```dts +$set(props: Partial): void; +``` + +
+ +
+ +- deprecated This method only exists when using one of the legacy compatibility helpers, which +is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) +for more info. + +
+ +
+
+ + + +## SvelteComponentTyped + +
+ +Use `Component` instead. See [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information. + +
+ +
+ +```dts +class SvelteComponentTyped< + Props extends Record = Record, + Events extends Record = any, + Slots extends Record = any +> extends SvelteComponent {} +``` + +
+ + + ## afterUpdate -
+
-Use `$effect` instead — see https://svelte.dev/docs/svelte/$effect +Use [`$effect`](/docs/svelte/$effect) instead
@@ -52,9 +197,9 @@ function afterUpdate(fn: () => void): void; ## beforeUpdate -
+
-Use `$effect.pre` instead — see https://svelte.dev/docs/svelte/$effect#$effect.pre +Use [`$effect.pre`](/docs/svelte/$effect#$effect.pre) instead
@@ -76,9 +221,9 @@ function beforeUpdate(fn: () => void): void; ## createEventDispatcher -
+
-Use callback props and/or the `$host()` rune instead — see https://svelte.dev/docs/svelte/v5-migration-guide#Event-changes-Component-events +Use callback props and/or the `$host()` rune instead — see [migration guide](/docs/svelte/v5-migration-guide#Event-changes-Component-events)
@@ -332,10 +477,32 @@ function tick(): Promise; Unmounts a component that was previously mounted using `mount` or `hydrate`. +Since 5.13.0, if `options.outro` is `true`, [transitions](/docs/svelte/transition) will play before the component is removed from the DOM. + +Returns a `Promise` that resolves after transitions have completed if `options.outro` is true, or immediately otherwise (prior to 5.13.0, returns `void`). + +```js +// @errors: 7031 +import { mount, unmount } from 'svelte'; +import App from './App.svelte'; + +const app = mount(App, { target: document.body }); + +// later... +unmount(app, { outro: true }); +``` +
```dts -function unmount(component: Record): void; +function unmount( + component: Record, + options?: + | { + outro?: boolean; + } + | undefined +): Promise; ```
@@ -409,13 +576,13 @@ interface Component< ): { /** * @deprecated This method only exists when using one of the legacy compatibility helpers, which - * is a stop-gap solution. See https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes + * is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) * for more info. */ $on?(type: string, callback: (e: any) => void): () => void; /** * @deprecated This method only exists when using one of the legacy compatibility helpers, which - * is a stop-gap solution. See https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes + * is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) * for more info. */ $set?(props: Partial): void; @@ -449,11 +616,11 @@ The custom element version of the component. Only present if compiled with the ` ## ComponentConstructorOptions -
+
In Svelte 4, components are classes. In Svelte 5, they are functions. Use `mount` instead to instantiate components. -See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) +See [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.
@@ -549,7 +716,7 @@ $$inline?: boolean; ## ComponentEvents -
+
The new `Component` type does not have a dedicated Events type. Use `ComponentProps` instead. @@ -626,7 +793,7 @@ type ComponentProps< ## ComponentType -
+
This type is obsolete when working with the new `Component` type. @@ -733,7 +900,7 @@ let { banner }: { banner: Snippet<[{ text: string }]> } = $props(); ``` You can only call a snippet through the `{@render ...}` tag. -/docs/svelte/snippet +See the [snippet documentation](/docs/svelte/snippet) for more info.
@@ -758,142 +925,4 @@ interface Snippet {/*…*/}
-## SvelteComponent - -This was the base class for Svelte components in Svelte 4. Svelte 5+ components -are completely different under the hood. For typing, use `Component` instead. -To instantiate components, use `mount` instead`. -See [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info. - -
- -```dts -class SvelteComponent< - Props extends Record = Record, - Events extends Record = any, - Slots extends Record = any -> {/*…*/} -``` - -
- -```dts -static element?: typeof HTMLElement; -``` - -
- -The custom element version of the component. Only present if compiled with the `customElement` compiler option - -
-
- -
- -```dts -[prop: string]: any; -``` - -
-
- -
- -```dts -constructor(options: ComponentConstructorOptions>); -``` - -
- -
- -- deprecated This constructor only exists when using the `asClassComponent` compatibility helper, which -is a stop-gap solution. Migrate towards using `mount` instead. See -https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes for more info. - -
- -
-
- -
- -```dts -$destroy(): void; -``` - -
- -
- -- deprecated This method only exists when using one of the legacy compatibility helpers, which -is a stop-gap solution. See https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes -for more info. - -
- -
-
- -
- -```dts -$on>( - type: K, - callback: (e: Events[K]) => void -): () => void; -``` - -
- -
- -- deprecated This method only exists when using one of the legacy compatibility helpers, which -is a stop-gap solution. See https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes -for more info. - -
- -
-
- -
- -```dts -$set(props: Partial): void; -``` - -
- -
- -- deprecated This method only exists when using one of the legacy compatibility helpers, which -is a stop-gap solution. See https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes -for more info. - -
- -
-
- -## SvelteComponentTyped - -
- -Use `Component` instead. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information. - -
- -
- -```dts -class SvelteComponentTyped< - Props extends Record = Record, - Events extends Record = any, - Slots extends Record = any -> extends SvelteComponent {} -``` - -
- diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-action.md b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-action.md index 5ec1ccf3b4..5015f3e6c3 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-action.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-action.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: svelte/action --- diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-animate.md b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-animate.md index 466f185778..82c4a56dff 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-animate.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-animate.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: svelte/animate --- diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-compiler.md b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-compiler.md index 229a67b459..5cbbff0806 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-compiler.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/21-svelte-compiler.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: svelte/compiler --- @@ -21,8 +22,6 @@ import { The current version, as set in package.json. -/docs/svelte-compiler#svelte-version -
```dts @@ -110,6 +109,7 @@ function parse( options: { filename?: string; modern: true; + loose?: boolean; } ): AST.Root; ``` @@ -125,6 +125,7 @@ function parse( | { filename?: string; modern?: false; + loose?: boolean; } | undefined ): Record; @@ -159,7 +160,7 @@ function preprocess( ## walk -
+
Replace this with `import { walk } from 'estree-walker'` @@ -202,7 +203,7 @@ namespace AST { options: SvelteOptions | null; fragment: Fragment; /** The parsed ` +``` + ### element_invalid_self_closing_tag ``` Self-closing HTML tags for non-void elements are ambiguous — use `<%name% ...>` rather than `<%name% ... />` ``` +In HTML, there's [no such thing as a self-closing tag](https://jakearchibald.com/2023/against-self-closing-tags-in-html/). While this _looks_ like a self-contained element with some text next to it... + +```html +
+ some text! +
+``` + +...a spec-compliant HTML parser (such as a browser) will in fact parse it like this, with the text _inside_ the icon: + +```html +
+ some text! +
+``` + +Some templating languages (including Svelte) will 'fix' HTML by turning `` into ``. Others adhere to the spec. Both result in ambiguity and confusion when copy-pasting code between different contexts, and as such Svelte prompts you to resolve the ambiguity directly by having an explicit closing tag. + +To automate this, run the dedicated migration: + +```bash +npx sv migrate self-closing-tags +``` + +In a future version of Svelte, self-closing tags may be upgraded from a warning to an error. + ### event_directive_deprecated ``` Using `on:%name%` to listen to the %name% event is deprecated. Use the event attribute `on%name%` instead ``` +See [the migration guide](v5-migration-guide#Event-changes) for more info. + ### export_let_unused ``` @@ -660,15 +703,17 @@ Component has unused export property '%name%'. If it is for external reference o Svelte 5 components are no longer classes. Instantiate them using `mount` or `hydrate` (imported from 'svelte') instead. ``` +See the [migration guide](v5-migration-guide#Components-are-no-longer-classes) for more info. + ### node_invalid_placement_ssr ``` -%thing% is invalid inside `<%parent%>`. When rendering this component on the server, the resulting HTML will be modified by the browser, likely resulting in a `hydration_mismatch` warning +%message%. When rendering this component on the server, the resulting HTML will be modified by the browser (by moving, removing, or inserting elements), likely resulting in a `hydration_mismatch` warning ``` HTML restricts where certain elements can appear. In case of a violation the browser will 'repair' the HTML in a way that breaks Svelte's assumptions about the structure of your components. Some examples: -- `

hello

world

` will result in `

hello

world

` for example (the `
` autoclosed the `

` because `

` cannot contain block-level elements) +- `

hello

world

` will result in `

hello

world

` (the `
` autoclosed the `

` because `

` cannot contain block-level elements) - `

option a
` will result in `` (the `
` is removed) - `
cell
` will result in `
cell
` (a `` is auto-inserted) @@ -680,6 +725,30 @@ This code will work when the component is rendered on the client (which is why t `%name%` is updated, but is not declared with `$state(...)`. Changing its value will not correctly trigger updates ``` +This warning is thrown when the compiler detects the following: +- a variable was declared without `$state` or `$state.raw` +- the variable is reassigned +- the variable is read in a reactive context + +In this case, changing the value will not correctly trigger updates. Example: + +```svelte + + +

This value updates: {reactive}

+

This value does not update: {stale}

+ + +``` + +To fix this, wrap your variable declaration with `$state`. + ### options_deprecated_accessors ``` @@ -746,18 +815,18 @@ Reactive declarations only exist at the top level of the instance script Reassignments of module-level declarations will not cause reactive statements to update ``` -### reactive_declaration_non_reactive_property - -``` -Properties of objects and arrays are not reactive unless in runes mode. Changes to this property will not cause the reactive statement to update -``` - ### script_context_deprecated ``` `context="module"` is deprecated, use the `module` attribute instead ``` +```svelte + +``` + ### script_unknown_attribute ``` @@ -770,12 +839,79 @@ Unrecognized attribute — should be one of `generics`, `lang` or `module`. If t Using `` to render parent content is deprecated. Use `{@render ...}` tags instead ``` +See [the migration guide](v5-migration-guide#Snippets-instead-of-slots) for more info. + ### state_referenced_locally ``` State referenced in its own scope will never update. Did you mean to reference it inside a closure? ``` +This warning is thrown when the compiler detects the following: +- A reactive variable is declared +- the variable is reassigned +- the variable is referenced inside the same scope it is declared and it is a non-reactive context + +In this case, the state reassignment will not be noticed by whatever you passed it to. For example, if you pass the state to a function, that function will not notice the updates: + +```svelte + + + + +``` + +```svelte + + + + +

The count is {count}

+``` + +To fix this, reference the variable such that it is lazily evaluated. For the above example, this can be achieved by wrapping `count` in a function: + +```svelte + + + + +``` + +```svelte + + + + +

The count is {+++count()+++}

+``` + +For more info, see [Passing state into functions]($state#Passing-state-into-functions). + ### store_rune_conflict ``` @@ -831,6 +967,8 @@ A derived value may be used in other contexts: `` is deprecated — use self-imports (e.g. `import %name% from './%basename%'`) instead ``` +See [the note in the docs](legacy-svelte-self) for more info. + ### unknown_code ``` diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/30-runtime-errors.md b/apps/svelte.dev/content/docs/svelte/98-reference/30-runtime-errors.md index cecb8045ab..e06883950e 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/30-runtime-errors.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/30-runtime-errors.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: 'Runtime errors' --- @@ -27,15 +28,19 @@ A component is attempting to bind to a non-bindable property `%key%` belonging t ### component_api_changed ``` -%parent% called `%method%` on an instance of %component%, which is no longer valid in Svelte 5. See https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes for more information +%parent% called `%method%` on an instance of %component%, which is no longer valid in Svelte 5 ``` +See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information. + ### component_api_invalid_new ``` -Attempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working. See https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes for more information +Attempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working. ``` +See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information. + ### derived_references_self ``` @@ -147,6 +152,8 @@ Updating state inside a derived or a template expression is forbidden. If the va `%name%(...)` is not available on the server ``` +Certain methods such as `mount` cannot be invoked while running in a server context. Avoid calling them eagerly, i.e. not during render. + ## Shared errors @@ -158,12 +165,54 @@ Updating state inside a derived or a template expression is forbidden. If the va Cannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet instead ``` +This error would be thrown in a setup like this: + +```svelte + + + {entry} + +``` + +```svelte + + + +
    + {#each items as item} +
  • {@render children(item)}
  • + {/each} +
+``` + +Here, `List.svelte` is using `{@render children(item)` which means it expects `Parent.svelte` to use snippets. Instead, `Parent.svelte` uses the deprecated `let:` directive. This combination of APIs is incompatible, hence the error. + ### lifecycle_outside_component ``` `%name%(...)` can only be used during component initialisation ``` +Certain lifecycle methods can only be used during component initialisation. To fix this, make sure you're invoking the method inside the _top level of the instance script_ of your component. + +```svelte + + + +``` + ### store_invalid_shape ``` diff --git a/apps/svelte.dev/content/docs/svelte/98-reference/30-runtime-warnings.md b/apps/svelte.dev/content/docs/svelte/98-reference/30-runtime-warnings.md index c1c79d53e4..51853aa42d 100644 --- a/apps/svelte.dev/content/docs/svelte/98-reference/30-runtime-warnings.md +++ b/apps/svelte.dev/content/docs/svelte/98-reference/30-runtime-warnings.md @@ -1,4 +1,5 @@ --- +NOTE: do not edit this file, it is generated in apps/svelte.dev/scripts/sync-docs/index.ts title: 'Runtime warnings' --- @@ -6,6 +7,40 @@ title: 'Runtime warnings' +### assignment_value_stale + +``` +Assignment to `%property%` property (%location%) will evaluate to the right-hand side, not the value of `%property%` following the assignment. This may result in unexpected behaviour. +``` + +Given a case like this... + +```svelte + + + +

items: {JSON.stringify(object.items)}

+``` + +...the array being pushed to when the button is first clicked is the `[]` on the right-hand side of the assignment, but the resulting value of `object.array` is an empty state proxy. As a result, the pushed value will be discarded. + +You can fix this by separating it into two statements: + +```js +let object = { array: [0] }; +// ---cut--- +function add() { + object.array ??= []; + object.array.push(object.array.length); +} +``` + ### binding_property_non_reactive ``` @@ -24,7 +59,7 @@ Your `console.%method%` contained `$state` proxies. Consider using `$inspect(... When logging a [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), browser devtools will log the proxy itself rather than the value it represents. In the case of Svelte, the 'target' of a `$state` proxy might not resemble its current value, which can be confusing. -The easiest way to log a value as it changes over time is to use the [`$inspect`](https://svelte.dev/docs/svelte/$inspect) rune. Alternatively, to log things on a one-off basis (for example, inside an event handler) you can use [`$state.snapshot`](https://svelte.dev/docs/svelte/$state#$state.snapshot) to take a snapshot of the current value. +The easiest way to log a value as it changes over time is to use the [`$inspect`](/docs/svelte/$inspect) rune. Alternatively, to log things on a one-off basis (for example, inside an event handler) you can use [`$state.snapshot`](/docs/svelte/$state#$state.snapshot) to take a snapshot of the current value. ### event_handler_invalid @@ -38,6 +73,31 @@ The easiest way to log a value as it changes over time is to use the [`$inspect` The `%attribute%` attribute on `%html%` changed its value between server and client renders. The client value, `%value%`, will be ignored in favour of the server value ``` +Certain attributes like `src` on an `` element will not be repaired during hydration, i.e. the server value will be kept. That's because updating these attributes can cause the image to be refetched (or in the case of an `