From 3b38d967c59c21a8dc3eb3d77811a1ce0f7ced77 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 14 Oct 2024 20:06:07 -0400 Subject: [PATCH 1/4] sync --- .../docs/kit/20-core-concepts/30-form-actions.md | 4 +++- .../kit/25-build-and-deploy/90-adapter-vercel.md | 2 ++ .../content/docs/kit/30-advanced/70-packaging.md | 13 +++++++++---- .../docs/kit/98-reference/10-@sveltejs-kit.md | 4 +++- .../docs/kit/98-reference/50-configuration.md | 4 +++- 5 files changed, 20 insertions(+), 7 deletions(-) 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 5a9d252a1d..9fd11a7f62 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 @@ -346,6 +346,8 @@ The easiest way to progressively enhance a form is to add the `use:enhance` acti
``` +> `use:enhance` can only be used with forms that have `method="POST"`. It will not work with `method="GET"`, which is the default for forms without a specified method. Attempting to use `use:enhance` on forms without `method="POST"` will result in an error. + > [!NOTE] Yes, it's a little confusing that the `enhance` action and `` are both called 'action'. These docs are action-packed. Sorry. Without an argument, `use:enhance` will emulate the browser-native behaviour, just without the full-page reloads. It will: @@ -507,7 +509,7 @@ Some forms don't need to `POST` data to the server — search inputs, for exampl
``` 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 2846b772c5..31639eb162 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 @@ -118,6 +118,8 @@ export const config = { The `expiration` property is required; all others are optional. +> Pages that are [prerendered](/docs/page-options#prerender) will ignore ISR configuration. + ## Environment variables Vercel makes a set of [deployment-specific environment variables](https://vercel.com/docs/concepts/projects/environment-variables#system-environment-variables) available. Like other environment variables, these are accessible from `$env/static/private` and `$env/dynamic/private` (sometimes — more on that later), and inaccessible from their public counterparts. To access one of these variables from the client: diff --git a/apps/svelte.dev/content/docs/kit/30-advanced/70-packaging.md b/apps/svelte.dev/content/docs/kit/30-advanced/70-packaging.md index 9d093d8008..3bb23d73d3 100644 --- a/apps/svelte.dev/content/docs/kit/30-advanced/70-packaging.md +++ b/apps/svelte.dev/content/docs/kit/30-advanced/70-packaging.md @@ -128,9 +128,9 @@ This is a legacy field that enabled tooling to recognise Svelte component librar ### sideEffects -The `sideEffects` field in `package.json` is used by bundlers to determine if a module may contain code that has side-effects. A module is considered to have side-effects if it makes changes that are observable from other scripts outside the module when it's imported. For example, side-effects include modifying global variables or the prototype of built-in JavaScript objects. Because a side-effect could potentially affect the behavior of other parts of the application, these files/modules will be included in the final bundle regardless of whether their exports are used in the application. It is a best practice to avoid side-effects in your code. +The `sideEffects` field in `package.json` is used by bundlers to determine if a module may contain code that has side effects. A module is considered to have side effects if it makes changes that are observable from other scripts outside the module when it's imported. For example, side effects include modifying global variables or the prototype of built-in JavaScript objects. Because a side effect could potentially affect the behavior of other parts of the application, these files/modules will be included in the final bundle regardless of whether their exports are used in the application. It is a best practice to avoid side effects in your code. -Setting the `sideEffects` field in `package.json` can help the bundler to be more aggressive in eliminating unused exports from the final bundle, a process known as tree-shaking. This results in smaller and more efficient bundles. Different bundlers handle `sideEffects` in various manners. While not necessary for Vite, we recommend that libraries state that all CSS files have side-effects so that your library will be [compatible with webpack](https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free). +Setting the `sideEffects` field in `package.json` can help the bundler to be more aggressive in eliminating unused exports from the final bundle, a process known as tree-shaking. This results in smaller and more efficient bundles. Different bundlers handle `sideEffects` in various manners. While not necessary for Vite, we recommend that libraries state that all CSS files have side effects so that your library will be [compatible with webpack](https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free). This is the configuration that comes with newly created projects: ```json /// file: package.json @@ -139,12 +139,17 @@ Setting the `sideEffects` field in `package.json` can help the bundler to be mor } ``` -Make sure that `"sideEffects"` is correctly set. If a file with side effects is incorrectly marked as having no side effects, it can result in broken functionality. If your package has files with side effects, you can specify them in an array: +> If the scripts in your library have side effects, ensure that you update the `sideEffects` field. All scripts are marked as side effect free by default in newly created projects. If a file with side effects is incorrectly marked as having no side effects, it can result in broken functionality. + +If your package has files with side effects, you can specify them in an array: ```json /// file: package.json { - "sideEffects": ["**/*.css", "./src/sideEffectfulFile.js"] + "sideEffects": [ + "**/*.css", + "./dist/sideEffectfulFile.js" + ] } ``` 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 eebb6debe9..0e2d348a5e 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 @@ -392,8 +392,10 @@ const config = { directives: { 'script-src': ['self'] }, + // must be specified with either the `report-uri` or `report-to` directives, or both reportOnly: { - 'script-src': ['self'] + 'script-src': ['self'], + 'report-uri': ['/'] } } } 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 a5da3e4d3c..fc0fa3ebb1 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 @@ -222,8 +222,10 @@ const config = { directives: { 'script-src': ['self'] }, + // must be specified with either the `report-uri` or `report-to` directives, or both reportOnly: { - 'script-src': ['self'] + 'script-src': ['self'], + 'report-uri': ['/'] } } } From e87593e03cb9869f6f3a0d7e9fc7ca32914cd5d6 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 14 Oct 2024 22:41:16 -0400 Subject: [PATCH 2/4] sync/fix --- .../kit/10-getting-started/10-introduction.md | 2 +- .../30-project-structure.md | 4 +- .../10-getting-started/40-web-standards.md | 2 +- .../docs/kit/20-core-concepts/10-routing.md | 6 +- .../docs/kit/20-core-concepts/20-load.md | 28 +- .../kit/20-core-concepts/30-form-actions.md | 8 +- .../kit/20-core-concepts/40-page-options.md | 14 +- .../20-core-concepts/50-state-management.md | 4 +- .../10-building-your-app.md | 2 +- .../25-build-and-deploy/40-adapter-node.md | 20 +- .../25-build-and-deploy/50-adapter-static.md | 2 +- .../60-adapter-cloudflare.md | 4 +- .../70-adapter-cloudflare-workers.md | 6 +- .../25-build-and-deploy/90-adapter-vercel.md | 4 +- .../kit/30-advanced/10-advanced-routing.md | 6 +- .../content/docs/kit/30-advanced/20-hooks.md | 4 +- .../content/docs/kit/30-advanced/25-errors.md | 4 +- .../docs/kit/30-advanced/30-link-options.md | 4 +- .../kit/30-advanced/40-service-workers.md | 2 +- .../kit/30-advanced/50-server-only-modules.md | 2 +- .../kit/30-advanced/67-shallow-routing.md | 2 +- .../docs/kit/30-advanced/70-packaging.md | 10 +- .../kit/40-best-practices/05-performance.md | 10 +- .../docs/kit/40-best-practices/07-images.md | 2 +- .../kit/40-best-practices/10-accessibility.md | 8 +- .../docs/kit/40-best-practices/20-seo.md | 6 +- .../content/docs/kit/60-appendix/10-faq.md | 4 +- .../docs/kit/60-appendix/20-integrations.md | 2 +- .../30-migrating-to-sveltekit-2.md | 4 +- .../docs/kit/60-appendix/40-migrating.md | 18 +- .../docs/kit/98-reference/10-@sveltejs-kit.md | 2066 +++++++++++++---- .../docs/kit/98-reference/50-configuration.md | 4 + .../content/docs/kit/98-reference/54-types.md | 2 +- .../docs/svelte/03-runes/02-side-effects.md | 4 +- .../04-runtime/04-imperative-component-api.md | 2 +- .../docs/svelte/05-misc/04-custom-elements.md | 4 +- .../svelte/98-reference/21-svelte-compiler.md | 2 +- apps/svelte.dev/scripts/sync-docs/index.ts | 16 +- apps/svelte.dev/svelte.config.js | 3 +- packages/site-kit/src/lib/markdown/utils.ts | 1 + .../site-kit/src/lib/server/content/index.ts | 2 +- 41 files changed, 1790 insertions(+), 510 deletions(-) diff --git a/apps/svelte.dev/content/docs/kit/10-getting-started/10-introduction.md b/apps/svelte.dev/content/docs/kit/10-getting-started/10-introduction.md index b9d6a62482..52e2eab278 100644 --- a/apps/svelte.dev/content/docs/kit/10-getting-started/10-introduction.md +++ b/apps/svelte.dev/content/docs/kit/10-getting-started/10-introduction.md @@ -12,7 +12,7 @@ title: Introduction SvelteKit is a framework for rapidly developing robust, performant web applications using [Svelte](https://svelte.dev/). If you're coming from React, SvelteKit is similar to Next. If you're coming from Vue, SvelteKit is similar to Nuxt. -To learn more about the kinds of applications you can build with SvelteKit, see the [FAQ](faq#what-can-i-make-with-sveltekit). +To learn more about the kinds of applications you can build with SvelteKit, see the [FAQ](faq#What-can-I-make-with-SvelteKit). ## What is Svelte? diff --git a/apps/svelte.dev/content/docs/kit/10-getting-started/30-project-structure.md b/apps/svelte.dev/content/docs/kit/10-getting-started/30-project-structure.md index c0962bc5ba..5b7ac9a3cc 100644 --- a/apps/svelte.dev/content/docs/kit/10-getting-started/30-project-structure.md +++ b/apps/svelte.dev/content/docs/kit/10-getting-started/30-project-structure.md @@ -40,7 +40,7 @@ The `src` directory contains the meat of your project. Everything except `src/ro - `lib` contains your library code (utilities and components), which can be imported via the [`$lib`]($lib) alias, or packaged up for distribution using [`svelte-package`](packaging) - `server` contains your server-only library code. It can be imported by using the [`$lib/server`](server-only-modules) alias. SvelteKit will prevent you from importing these in client code. -- `params` contains any [param matchers](advanced-routing#matching) your app needs +- `params` contains any [param matchers](advanced-routing#Matching) your app needs - `routes` contains the [routes](routing) of your application. You can also colocate other components that are only used within a single route here - `app.html` is your page template — an HTML document containing the following placeholders: - `%sveltekit.head%` — `` and ` + +

{data.count}

+ +``` + + + + +

+ +```dts +untrack(fn: () => T): T; +``` + +
+ +Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: + +```js +// @errors: 7031 +/// file: src/routes/+page.server.js +export async function load({ untrack, url }) { + // Untrack url.pathname so that path changes don't trigger a rerun + if (untrack(() => url.pathname === '/')) { + return { message: 'Welcome!' }; + } +} +``` + +
+
+ +## LoadProperties + +
+ +```dts +type LoadProperties< + input extends Record | void +> = input extends void + ? undefined // needs to be undefined, because void will break intellisense + : input extends Record + ? input + : unknown; +``` + +
+ +## Navigation + +
+ +```dts +interface Navigation {/*…*/} +``` + +
+ +```dts +from: NavigationTarget | null; +``` + +
+ +Where navigation was triggered from + +
+
+ +
+ +```dts +to: NavigationTarget | null; +``` + +
+ +Where navigation is going to/has gone to + +
+
+ +
+ +```dts +type: Exclude; +``` + +
+ +The type of navigation: +- `form`: The user submitted a `
` +- `leave`: The app is being left either because the tab is being closed or a navigation to a different document is occurring +- `link`: Navigation was triggered by a link click +- `goto`: Navigation was triggered by a `goto(...)` call or a redirect +- `popstate`: Navigation was triggered by back/forward navigation + +
+
+ +
+ +```dts +willUnload: boolean; +``` + +
+ +Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation) + +
+
+ +
+ +```dts +delta?: number; +``` + +
+ +In case of a history back/forward navigation, the number of steps to go back/forward + +
+
+ +
+ +```dts +complete: Promise; +``` + +
+ +A promise that resolves once the navigation is complete, and rejects if the navigation +fails or is aborted. In the case of a `willUnload` navigation, the promise will never resolve + +
+
+ +## NavigationEvent + +
+ +```dts +interface NavigationEvent< + Params extends Partial> = Partial< + Record + >, + RouteId extends string | null = string | null +> {/*…*/} +``` + +
+ +```dts +params: Params; +``` + +
+ +The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + +
+
+ +
+ +```dts +route: {/*…*/} +``` + +
+ +Info about the current route + +
+ +```dts +id: RouteId; +``` + +
+ +The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + +
+
+ +
+
+ +
+ +```dts +url: URL; +``` + +
+ +The URL of the current page + +
+
+ +## NavigationTarget + +Information about the target of a specific navigation. + +
+ +```dts +interface NavigationTarget {/*…*/} +``` + +
+ +```dts +params: Record | null; +``` + +
+ +Parameters of the target page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object. +Is `null` if the target is not part of the SvelteKit app (could not be resolved to a route). + +
+
+ +
+ +```dts +route: { id: string | null }; +``` + +
+ +Info about the target route + +
+
+ +
+ +```dts +url: URL; +``` + +
+ +The URL that is navigated to + +
+
+ +## NavigationType + +- `enter`: The app has hydrated +- `form`: The user submitted a `` with a GET method +- `leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document +- `link`: Navigation was triggered by a link click +- `goto`: Navigation was triggered by a `goto(...)` call or a redirect +- `popstate`: Navigation was triggered by back/forward navigation + +
+ +```dts +type NavigationType = + | 'enter' + | 'form' + | 'leave' + | 'link' + | 'goto' + | 'popstate'; +``` + +
+ +## NumericRange + +
+ +```dts +type NumericRange< + TStart extends number, + TEnd extends number +> = Exclude, LessThan>; +``` + +
+ +## OnNavigate + +The argument passed to [`onNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-onnavigate) callbacks. + +
+ +```dts +interface OnNavigate extends Navigation {/*…*/} +``` + +
+ +```dts +type: Exclude; +``` + +
+ +The type of navigation: +- `form`: The user submitted a `` +- `link`: Navigation was triggered by a link click +- `goto`: Navigation was triggered by a `goto(...)` call or a redirect +- `popstate`: Navigation was triggered by back/forward navigation + +
+
+ +
+ +```dts +willUnload: false; +``` + +
+ +Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page. + +
+
+ +## Page + +The shape of the `$page` store + +
+ +```dts +interface Page< + Params extends Record = Record< + string, + string + >, + RouteId extends string | null = string | null +> {/*…*/} +``` + +
+ +```dts +url: URL; +``` + +
+ +The URL of the current page + +
+
+ +
+ +```dts +params: Params; +``` + +
+ +The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + +
+
+ +
+ +```dts +route: {/*…*/} +``` + +
+ +Info about the current route + +
+ +```dts +id: RouteId; +``` + +
+ +The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + +
+
+ +
+
+ +
+ +```dts +status: number; +``` + +
+ +Http status code of the current page + +
+
+ +
+ +```dts +error: App.Error | null; +``` + +
+ +The error object of the current page, if any. Filled from the `handleError` hooks. + +
+
+ +
+ +```dts +data: App.PageData & Record; +``` + +
+ +The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`. + +
+
+ +
+ +```dts +state: App.PageState; +``` + +
+ +The page state, which can be manipulated using the [`pushState`](https://kit.svelte.dev/docs/modules#$app-navigation-pushstate) and [`replaceState`](https://kit.svelte.dev/docs/modules#$app-navigation-replacestate) functions from `$app/navigation`. + +
+
+ +
+ +```dts +form: any; +``` + +
+ +Filled only after a form submission. See [form actions](https://kit.svelte.dev/docs/form-actions) for more info. + +
+
+ +## ParamMatcher + +The shape of a param matcher. See [matching](https://kit.svelte.dev/docs/advanced-routing#matching) for more info. + +
+ +```dts +type ParamMatcher = (param: string) => boolean; +``` + +
+ +## PrerenderOption + +
+ +```dts +type PrerenderOption = boolean | 'auto'; +``` + +
+ +## Redirect + +The object returned by the [`redirect`](https://kit.svelte.dev/docs/modules#sveltejs-kit-redirect) function + +
+ +```dts +interface Redirect {/*…*/} +``` + +
+ +```dts +status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308; +``` + +
+ +The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308. + +
+
+ +
+ +```dts +location: string; +``` + +
+ +The location to redirect to. + +
+
+ +## RequestEvent + +
+ +```dts +interface RequestEvent< + Params extends Partial> = Partial< + Record + >, + RouteId extends string | null = string | null +> {/*…*/} +``` + +
+ +```dts +cookies: Cookies; +``` + +
+ +Get or set cookies related to the current request + +
+
+ +
+ +```dts +fetch: typeof fetch; +``` + +
+ +`fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features: + +- 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://kit.svelte.dev/docs/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://kit.svelte.dev/docs/load#cookies) + +
+
+ +
+ +```dts +getClientAddress(): string; +``` + +
+ +The client's IP address, set by the adapter. + +
+
+ +
+ +```dts +locals: App.Locals; +``` + +
+ +Contains custom data that was added to the request within the [`handle hook`](https://kit.svelte.dev/docs/hooks#server-hooks-handle). + +
+
+ +
+ +```dts +params: Params; +``` + +
+ +The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object + +
+
+ +
+ +```dts +platform: Readonly | undefined; +``` + +
+ +Additional data made available through the adapter. + +
+
+ +
+ +```dts +request: Request; +``` + +
+ +The original request object + +
+
+ +
+ +```dts +route: {/*…*/} +``` + +
+ +Info about the current route + +
+ +```dts +id: RouteId; +``` + +
+ +The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]` + +
+
+ +
+
+ +
+ +```dts +setHeaders(headers: Record): void; +``` + +
+ +If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example: + +```js +// @errors: 7031 +/// file: src/routes/blog/+page.js +export async function load({ fetch, setHeaders }) { + const url = `https://cms.example.com/articles.json`; + const response = await fetch(url); + + setHeaders({ + age: response.headers.get('age'), + 'cache-control': response.headers.get('cache-control') + }); + + return response.json(); +} +``` -A root-relative path that must start, but not end with `/` (e.g. `/base-path`), unless it is the empty string. This specifies where your app is served from and allows the app to live on a non-root path. Note that you need to prepend all your root-relative links with the base value or they will point to the root of your domain, not your `base` (this is how the browser works). You can use [`base` from `$app/paths`](https://kit.svelte.dev/docs/modules#$app-paths-base) for that: `Link`. If you find yourself writing this often, it may make sense to extract this into a reusable component. +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://kit.svelte.dev/docs/types#public-types-cookies) API instead.
+
```dts -relative?: boolean; +url: URL; ```
-
- -- default `true` +The requested URL. +
-Whether to use relative asset paths. - -If `true`, `base` and `assets` imported from `$app/paths` will be replaced with relative asset paths during server-side rendering, resulting in more portable HTML. -If `false`, `%sveltekit.assets%` and references to build artifacts will always be root-relative paths, unless `paths.assets` is an external URL - -[Single-page app](https://kit.svelte.dev/docs/single-page-apps) fallback pages will always use absolute paths, regardless of this setting. +
-If your app uses a `` element, you should set this to `false`, otherwise asset URLs will incorrectly be resolved against the `` URL rather than the current page. +```dts +isDataRequest: boolean; +``` -In 1.0, `undefined` was a valid value, which was set by default. In that case, if `paths.assets` was not external, SvelteKit would replace `%sveltekit.assets%` with a relative path and use relative paths to reference build artifacts, but `base` and `assets` imported from `$app/paths` would be as specified in your config. +
-
-
+`true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information +related to the data request in this case. Use this property instead if the distinction is important to you.
@@ -956,335 +1989,574 @@ In 1.0, `undefined` was a valid value, which was set by default. In that case, i
```dts -prerender?: {/*…*/} +isSubRequest: boolean; ```
-See [Prerendering](https://kit.svelte.dev/docs/page-options#prerender). +`true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server. -
+
+
+ +## RequestHandler + +A `(event: RequestEvent) => Response` function exported from a `+server.js` file that corresponds to an HTTP verb (`GET`, `PUT`, `PATCH`, etc) and handles requests with that method. + +It receives `Params` as the first generic argument, which you can skip by using [generated types](https://kit.svelte.dev/docs/types#generated-types) instead. + +
```dts -concurrency?: number; +type RequestHandler< + Params extends Partial> = Partial< + Record + >, + RouteId extends string | null = string | null +> = ( + event: RequestEvent +) => MaybePromise; ``` -
+
-
+## Reroute -- default `1` +The [`reroute`](https://kit.svelte.dev/docs/hooks#universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render. -
+
-How many pages can be prerendered simultaneously. JS is single-threaded, but in cases where prerendering performance is network-bound (for example loading content from a remote CMS) this can speed things up by processing other tasks while waiting on the network response. +```dts +type Reroute = (event: { url: URL }) => void | string; +```
-
+ +## ResolveOptions + +
+ +```dts +interface ResolveOptions {/*…*/} +``` +
```dts -crawl?: boolean; +transformPageChunk?(input: { html: string; done: boolean }): MaybePromise; ```
-- default `true` +- `input` the html chunk and the info if this is the last chunk
-Whether SvelteKit should find pages to prerender by following links from `entries`. +Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML +(they could include an element's opening tag but not its closing tag, for example) +but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components.
+
```dts -entries?: Array<'*' | `/${string}`>; +filterSerializedResponseHeaders?(name: string, value: string): boolean; ```
-- default `["*"]` +- `name` header name +- `value` header value
-An array of pages to prerender, or start crawling from (if `crawl: true`). The `*` string includes all routes containing no required `[parameters]` with optional parameters included as being empty (since SvelteKit doesn't know what value any parameters should have). +Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`. +By default, none will be included.
+
```dts -handleHttpError?: PrerenderHttpErrorHandlerValue; +preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean; ```
-- default `"fail"` +- `input` the type of the file and its path + +
+ +Determines what should be added to the `` tag to preload it. +By default, `js` and `css` files will be preloaded.
+
-How to respond to HTTP errors encountered while prerendering the app. +## RouteDefinition -- `'fail'` — fail the build -- `'ignore'` - silently ignore the failure and continue -- `'warn'` — continue, but print a warning -- `(details) => void` — a custom error handler that takes a `details` object with `status`, `path`, `referrer`, `referenceType` and `message` properties. If you `throw` from this function, the build will fail +
-```js -// @errors: 7031 -/// file: svelte.config.js -/** @type {import('@sveltejs/kit').Config} */ -const config = { - kit: { - prerender: { - handleHttpError: ({ path, referrer, message }) => { - // ignore deliberate link to shiny 404 page - if (path === '/not-found' && referrer === '/blog/how-we-built-our-404-page') { - return; - } - - // otherwise fail the build - throw new Error(message); - } - } - } -}; +```dts +interface RouteDefinition {/*…*/} ``` -
-
```dts -handleMissingId?: PrerenderMissingIdHandlerValue; +id: string; ``` -
+
+
-
+
-- default `"fail"` +```dts +api: { + methods: Array; +}; +``` +
-How to respond when hash links from one prerendered page to another don't correspond to an `id` on the destination page. +
-- `'fail'` — fail the build -- `'ignore'` - silently ignore the failure and continue -- `'warn'` — continue, but print a warning -- `(details) => void` — a custom error handler that takes a `details` object with `path`, `id`, `referrers` and `message` properties. If you `throw` from this function, the build will fail +```dts +page: { + methods: Array>; +}; +``` +
-
+
```dts -handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue; +pattern: RegExp; ``` -
+
+
-
+
-- default `"fail"` +```dts +prerender: PrerenderOption; +``` +
-How to respond when an entry generated by the `entries` export doesn't match the route it was generated from. +
-- `'fail'` — fail the build -- `'ignore'` - silently ignore the failure and continue -- `'warn'` — continue, but print a warning -- `(details) => void` — a custom error handler that takes a `details` object with `generatedFromId`, `entry`, `matchedId` and `message` properties. If you `throw` from this function, the build will fail +```dts +segments: RouteSegment[]; +``` +
+ +
+ +```dts +methods: Array; +``` + +
+
```dts -origin?: string; +config: Config; ``` -
+
+
-
+## SSRManifest + +
+ +```dts +interface SSRManifest {/*…*/} +``` -- default `"http://sveltekit-prerender"` +
+ +```dts +appDir: string; +``` +
-The value of `url.origin` during prerendering; useful if it is included in rendered content. +
+ +```dts +appPath: string; +``` +
-
+
+ +```dts +assets: Set; +``` + +
+ +
+ +```dts +mimeTypes: Record; +``` + +
```dts -serviceWorker?: {/*…*/} +_: {/*…*/} ```
+private fields +
```dts -register?: boolean; +client: NonNullable; ``` -
- -
+
+
+
-- default `true` +```dts +nodes: SSRNodeLoader[]; +``` +
+
-Whether to automatically register the service worker, if it exists. +```dts +routes: SSRRoute[]; +``` +
+
+ +```dts +matchers(): Promise>; +``` + +
```dts -files?(filepath: string): boolean; +server_assets: Record; ```
-
- -- default `(filename) => !/\.DS_Store/.test(filename)` +A `[file]: size` map of all assets imported by server code
- -Determine which files in your `static` directory will be available in `$service-worker.files`. +
+## Server + +
+ +```dts +class Server {/*…*/} +``` + +
+ +```dts +constructor(manifest: SSRManifest); +``` + +
+ +
+ +```dts +init(options: ServerInitOptions): Promise; +``` + +
```dts -typescript?: {/*…*/} +respond(request: Request, options: RequestOptions): Promise; ``` -
+
+
-
+## ServerInitOptions + +
```dts -config?: (config: Record) => Record | void; +interface ServerInitOptions {/*…*/} ``` -
+
-
+```dts +env: Record; +``` + +
-- default `(config) => config` +A map of environment variables
+
+ +
+ +```dts +read?: (file: string) => ReadableStream; +``` + +
-A function that allows you to edit the generated `tsconfig.json`. You can mutate the config (recommended) or return a new one. -This is useful for extending a shared `tsconfig.json` in a monorepo root, for example. +A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work
-
+## ServerLoad + +The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](https://kit.svelte.dev/docs/types#generated-types)) +rather than using `ServerLoad` directly. + +
+ +```dts +type ServerLoad< + Params extends Partial> = Partial< + Record + >, + ParentData extends Record = Record< + string, + any + >, + OutputData extends Record | void = Record< + string, + any + > | void, + RouteId extends string | null = string | null +> = ( + event: ServerLoadEvent +) => MaybePromise; +``` +
+## ServerLoadEvent + +
+ +```dts +interface ServerLoadEvent< + Params extends Partial> = Partial< + Record + >, + ParentData extends Record = Record< + string, + any + >, + RouteId extends string | null = string | null +> extends RequestEvent {/*…*/} +``` +
```dts -version?: {/*…*/} +parent(): Promise; ```
-Client-side navigation can be buggy if you deploy a new version of your app while people are using it. If the code for the new page is already loaded, it may have stale content; if it isn't, the app's route manifest may point to a JavaScript file that no longer exists. -SvelteKit helps you solve this problem through version management. -If SvelteKit encounters an error while loading the page and detects that a new version has been deployed (using the `name` specified here, which defaults to a timestamp of the build) it will fall back to traditional full-page navigation. -Not all navigations will result in an error though, for example if the JavaScript for the next page is already loaded. If you still want to force a full-page navigation in these cases, use techniques such as setting the `pollInterval` and then using `beforeNavigate`: -```html -/// file: +layout.svelte - -``` +Be careful not to introduce accidental waterfalls when using `await parent()`. If for example you only want to merge parent data into the returned output, call it _after_ fetching your other data. -If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of the [`updated`](https://kit.svelte.dev/docs/modules#$app-stores-updated) store to `true` when it detects one. +
+
-
+
```dts -name?: string; +depends(...deps: string[]): void; ```
-The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build. +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://kit.svelte.dev/docs/modules#$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`. -For example, to use the current commit hash, you could do use `git rev-parse HEAD`: +URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding). + +Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html). + +The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun. ```js // @errors: 7031 -/// file: svelte.config.js -import * as child_process from 'node:child_process'; - -export default { - kit: { - version: { - name: child_process.execSync('git rev-parse HEAD').toString().trim() - } +/// file: src/routes/+page.js +let count = 0; +export async function load({ depends }) { + depends('increase:count'); + + return { count: count++ }; +} +``` + +```html +/// file: src/routes/+page.svelte + + +

{data.count}

+ ```

+
```dts -pollInterval?: number; +untrack(fn: () => T): T; ```
-
+Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example: -- default `0` +```js +// @errors: 7031 +/// file: src/routes/+page.js +export async function load({ untrack, url }) { + // Untrack url.pathname so that path changes don't trigger a rerun + if (untrack(() => url.pathname === '/')) { + return { message: 'Welcome!' }; + } +} +```
+
+ +## Snapshot + +The type of `export const snapshot` exported from a page or layout component. + +
+ +```dts +interface Snapshot {/*…*/} +``` -The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs. +
+ +```dts +capture: () => T; +``` +
+ +
+ +```dts +restore: (snapshot: T) => void; +``` + +
+## SubmitFunction + +
+ +```dts +type SubmitFunction< + Success extends + | Record + | undefined = Record, + Failure extends + | Record + | undefined = Record +> = (input: { + action: URL; + formData: FormData; + formElement: HTMLFormElement; + controller: AbortController; + submitter: HTMLElement | null; + cancel(): void; +}) => MaybePromise< + | void + | ((opts: { + formData: FormData; + formElement: HTMLFormElement; + action: URL; + result: ActionResult; + /** + * Call this to get the default behavior of a form submission response. + * @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?: { + reset?: boolean; + invalidateAll?: boolean; + }): Promise; + }) => void) +>; +``` +
-
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 fc0fa3ebb1..be3ab99f59 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 @@ -26,6 +26,8 @@ const config = { export default config; ``` +## Config +
```dts @@ -124,6 +126,8 @@ Any additional options required by tooling that integrates with Svelte. +## KitConfig + The `kit` property configures SvelteKit, and can have the following properties: ## adapter diff --git a/apps/svelte.dev/content/docs/kit/98-reference/54-types.md b/apps/svelte.dev/content/docs/kit/98-reference/54-types.md index a556cd5805..80bae76fd2 100644 --- a/apps/svelte.dev/content/docs/kit/98-reference/54-types.md +++ b/apps/svelte.dev/content/docs/kit/98-reference/54-types.md @@ -84,7 +84,7 @@ export async function load({ params, fetch }) { } ``` -> [!NOTE] For this to work, your own `tsconfig.json` or `jsconfig.json` should extend from the generated `.svelte-kit/tsconfig.json` (where `.svelte-kit` is your [`outDir`](configuration#outdir)): +> [!NOTE] For this to work, your own `tsconfig.json` or `jsconfig.json` should extend from the generated `.svelte-kit/tsconfig.json` (where `.svelte-kit` is your [`outDir`](configuration#outDir)): > > `{ "extends": "./.svelte-kit/tsconfig.json" }` diff --git a/apps/svelte.dev/content/docs/svelte/03-runes/02-side-effects.md b/apps/svelte.dev/content/docs/svelte/03-runes/02-side-effects.md index 583d3c9bfa..c9bda9a1e6 100644 --- a/apps/svelte.dev/content/docs/svelte/03-runes/02-side-effects.md +++ b/apps/svelte.dev/content/docs/svelte/03-runes/02-side-effects.md @@ -164,7 +164,7 @@ In general, `$effect` is best considered something of an escape hatch — useful ``` -> [!NOTE] For things that are more complicated than a simple expression like `count * 2`, you can also use [`$derived.by`](#$derived-by). +> [!NOTE] For things that are more complicated than a simple expression like `count * 2`, you can also use `$derived.by`. You might be tempted to do something convoluted with effects to link one value to another. The following example shows two inputs for "money spent" and "money left" that are connected to each other. If you update one, the other should update accordingly. Don't use effects for this ([demo](/#H4sIAAAAAAAACpVRy2rDMBD8lWXJwYE0dg-9KFYg31H3oNirIJBlYa1DjPG_F8l1XEop9LgzOzP7mFAbSwHF-4ROtYQCL97jAXn0sQh3skx4wNANfR2RMtS98XyuXMWWGLhjZUHCa1GcVix4cgwSdoEVU1bsn4wl_Y1I2kS6inekNdWcZXuQZ5giFDWpfwl5WYyT2fynbB1g1UWbTVbm2w6utOpKNq1TGucHhri6rLBX7kYVwtW4RtyVHUhOyXeGVj3klLxnyJP0i8lXNJUx6en-v6A48K85kTimpi0sYj-yAo-Wlh9FcL1LY4K3ahSgLT1OC3ZTXkBxfKN2uVC6T5LjAduuMdpQg4L7geaP-RNHPuClMQIAAA==)): @@ -289,7 +289,7 @@ In rare cases, you may need to run code _before_ the DOM updates. For this we ca
``` -Apart from the timing, `$effect.pre` works exactly like [`$effect`](#$effect) — refer to its documentation for more info. +Apart from the timing, `$effect.pre` works exactly like `$effect` — refer to its documentation for more info. ## `$effect.tracking` diff --git a/apps/svelte.dev/content/docs/svelte/04-runtime/04-imperative-component-api.md b/apps/svelte.dev/content/docs/svelte/04-runtime/04-imperative-component-api.md index b4517bd34f..a124a86ba4 100644 --- a/apps/svelte.dev/content/docs/svelte/04-runtime/04-imperative-component-api.md +++ b/apps/svelte.dev/content/docs/svelte/04-runtime/04-imperative-component-api.md @@ -64,7 +64,7 @@ result.head; // HTML for somewhere in this tag ## `hydrate` -Like `mount`, but will reuse up any HTML rendered by Svelte's SSR output (from the [`render`](#server-render) function) inside the target and make it interactive: +Like `mount`, but will reuse up any HTML rendered by Svelte's SSR output (from the [`render`](#render) function) inside the target and make it interactive: ```js // @errors: 2322 diff --git a/apps/svelte.dev/content/docs/svelte/05-misc/04-custom-elements.md b/apps/svelte.dev/content/docs/svelte/05-misc/04-custom-elements.md index d2a75e25cb..39659f1950 100644 --- a/apps/svelte.dev/content/docs/svelte/05-misc/04-custom-elements.md +++ b/apps/svelte.dev/content/docs/svelte/05-misc/04-custom-elements.md @@ -4,7 +4,7 @@ title: Custom elements - [basically what we have today](https://svelte.dev/docs/custom-elements-api) -Svelte components can also be compiled to custom elements (aka web components) using the `customElement: true` compiler option. You should specify a tag name for the component using the `` [element](special-elements#svelte-options). +Svelte components can also be compiled to custom elements (aka web components) using the `customElement: true` compiler option. You should specify a tag name for the component using the `` [element](special-elements#svelte:options). ```svelte @@ -36,7 +36,7 @@ document.body.innerHTML = ` `; ``` -Any [props](basic-markup#attributes-and-props) are exposed as properties of the DOM element (as well as being readable/writable as attributes, where possible). +Any [props](basic-markup#Attributes-and-props) are exposed as properties of the DOM element (as well as being readable/writable as attributes, where possible). ```js // @noErrors 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 6f68a4e4db..1ab80cc87a 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 @@ -135,7 +135,7 @@ function parse( ## preprocess The preprocess function provides convenient hooks for arbitrarily transforming component source code. -For example, it can be used to convert a