`](../svelte/svelte-head) の内側に置くべきです。説明的な title と description の書き方に関するガイダンスと、検索エンジンにとってわかりやすいコンテンツを作るためのその他の方法については、Google の [Lighthouse SEO audits](https://web.dev/lighthouse-seo/) のドキュメントで見つけることができます。 ### サイトマップ [サイトマップ](https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap) は、検索エンジンがサイト内のページの優先順位付けをするのに役立ちます、特にコンテンツの量が多い場合は。エンドポイントを使用してサイトマップを動的に作成できます: ```js /// file: src/routes/sitemap.xml/+server.js export async function GET() { return new Response( ` `.trim(), { headers: { 'Content-Type': 'application/xml' } } ); } ``` ### AMP 現代の web 開発における不幸な現実として、サイトの [Accelerated Mobile Pages (AMP)](https://amp.dev/) バージョンを作らなければならないときがある、というのがあります。SvelteKit では、[`inlineStyleThreshold`](configuration#inlineStyleThreshold) オプションを設定することでこれを実現することができます… ```js /// file: svelte.config.js /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { // since isn't // allowed, inline all styles inlineStyleThreshold: Infinity } }; export default config; ``` …最上位(root)の `+layout.js`/`+layout.server.js` の `csr` を無効にします… ```js /// file: src/routes/+layout.server.js export const csr = false; ``` …`amp` を `app.html` に追加します ```html ... ``` …そして、`transformPageChunk` と、`@sveltejs/amp` からインポートできる `transform` を使用して、HTML を変換します: ```js /// file: src/hooks.server.js import * as amp from '@sveltejs/amp'; /** @type {import('@sveltejs/kit').Handle} */ export async function handle({ event, resolve }) { let buffer = ''; return await resolve(event, { transformPageChunk: ({ html, done }) => { buffer += html; if (done) return amp.transform(buffer); } }); } ``` ページを amp に変換した結果として未使用の CSS が配布されてしまうのを防ぎたければ、[`dropcss`](https://www.npmjs.com/package/dropcss) を使用すると良いでしょう: ```js // @filename: ambient.d.ts declare module 'dropcss'; // @filename: index.js // ---cut--- /// file: src/hooks.server.js // @errors: 2307 import * as amp from '@sveltejs/amp'; import dropcss from 'dropcss'; /** @type {import('@sveltejs/kit').Handle} */ export async function handle({ event, resolve }) { let buffer = ''; return await resolve(event, { transformPageChunk: ({ html, done }) => { buffer += html; if (done) { let css = ''; const markup = amp .transform(buffer) .replace('⚡', 'amp') // dropcss can't handle this character .replace(/`; }); css = dropcss({ css, html: markup }).css; return markup.replace('', `${css}`); } } }); } ```
# @sveltejs/kit
```js // @noErrors import { Server, VERSION, error, fail, isActionFailure, isHttpError, isRedirect, json, redirect, text } from '@sveltejs/kit'; ``` ## Server ```dts class Server {/*…*/} ```
```dts constructor(manifest: SSRManifest); ```
```dts init(options: ServerInitOptions): Promise
; ``` ```dts respond(request: Request, options: RequestOptions): Promise
; ``` ## VERSION ```dts const VERSION: string; ```
## error Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking `handleError`. Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it. ```dts function error(status: number, body: App.Error): never; ```
```dts function error( status: number, body?: { message: string; } extends App.Error ? App.Error | string | undefined : never ): never; ```
## fail Create an `ActionFailure` object. ```dts function fail(status: number): ActionFailure; ```
```dts function fail< T extends Record | undefined = undefined >(status: number, data: T): ActionFailure; ```
## isActionFailure Checks whether this is an action failure thrown by `fail`. ```dts function isActionFailure(e: unknown): e is ActionFailure; ```
## isHttpError Checks whether this is an error thrown by `error`. ```dts function isHttpError( e: unknown, status?: T | undefined ): e is HttpError_1 & { status: T extends undefined ? never : T; }; ```
## isRedirect Checks whether this is a redirect thrown by `redirect`. ```dts function isRedirect(e: unknown): e is Redirect_1; ```
## json Create a JSON `Response` object from the supplied data. ```dts function json( data: any, init?: ResponseInit | undefined ): Response; ```
## redirect 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 function redirect( status: | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number), location: string | URL ): never; ```
## text Create a `Response` object from the supplied body. ```dts function text( body: string, init?: ResponseInit | undefined ): Response; ```
## Action Shape of a form action method that is part of `export const actions = {..}` in `+page.server.js`. See [form actions](/docs/kit/form-actions) for more information. ```dts type Action< Params extends Partial
> = Partial< Record >, OutputData extends Record | void = Record< string, any > | void, RouteId extends string | null = string | null > = ( event: RequestEvent ) => MaybePromise; ``` ## ActionFailure ```dts interface ActionFailure< T extends Record
| undefined = undefined > {/*…*/} ``` ```dts status: number; ```
```dts [uniqueSymbol]: true; ```
## ActionResult When calling a form action via fetch, the response will be one of these shapes. ```svelte ` element that otherwise would work without JavaScript. The `submit` function is called upon submission with the given FormData and the `action` that should be triggered. If `cancel` is called, the form will not be submitted. You can use the abort `controller` to cancel the submission in case another one starts. If a function is returned, that function is called with the response from the server. 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` - 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 ```dts function enhance< Success extends Record | undefined, Failure extends Record | undefined >( form_element: HTMLFormElement, submit?: import('@sveltejs/kit').SubmitFunction< Success, Failure > ): { destroy(): void; }; ```
# $app/navigation
```js // @noErrors import { afterNavigate, beforeNavigate, disableScrollHandling, goto, invalidate, invalidateAll, onNavigate, preloadCode, preloadData, pushState, replaceState } from '$app/navigation'; ``` ## afterNavigate 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. ```dts function afterNavigate( callback: ( navigation: import('@sveltejs/kit').AfterNavigate ) => void ): void; ```
## beforeNavigate 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. When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`. If the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`. `beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted. ```dts function beforeNavigate( callback: ( navigation: import('@sveltejs/kit').BeforeNavigate ) => void ): void; ```
## disableScrollHandling If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling. This is generally discouraged, since it breaks user expectations. ```dts 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)`. ```dts function goto( url: string | URL, opts?: | { replaceState?: boolean | undefined; noScroll?: boolean | undefined; keepFocus?: boolean | undefined; invalidateAll?: boolean | undefined; invalidate?: | (string | URL | ((url: URL) => boolean))[] | undefined; state?: App.PageState | undefined; } | undefined ): Promise; ```
## invalidate Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated. If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters). To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL. The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned. This can be useful if you want to invalidate based on a pattern instead of a exact match. ```ts // Example: Match '/path' regardless of the query parameters import { invalidate } from '$app/navigation'; invalidate((url) => url.pathname === '/path'); ``` ```dts function invalidate( resource: string | URL | ((url: URL) => boolean) ): Promise; ```
## invalidateAll Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated. ```dts function invalidateAll(): Promise; ```
## onNavigate A lifecycle function that runs the supplied `callback` immediately before we navigate to a new URL except during full-page navigations. If you return a `Promise`, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use `document.startViewTransition`. Avoid promises that are slow to resolve, since navigation will appear stalled to the user. If a function (or a `Promise` that resolves to a function) is returned from the callback, it will be called once the DOM has updated. `onNavigate` must be called during a component initialization. It remains active as long as the component is mounted. ```dts function onNavigate( callback: ( navigation: import('@sveltejs/kit').OnNavigate ) => MaybePromise<(() => void) | void> ): void; ```
## preloadCode Programmatically imports the code for routes that haven't yet been fetched. Typically, you might call this to speed up subsequent navigation. You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`). Unlike `preloadData`, this won't call `load` functions. Returns a Promise that resolves when the modules have been imported. ```dts function preloadCode(pathname: string): Promise; ```
## preloadData Programmatically preloads the given page, which means 1. ensuring that the code for the page is loaded, and 2. calling the page's load function with the appropriate options. This is the same behaviour that SvelteKit triggers when the user taps or mouses over an `` element with `data-sveltekit-preload-data`. If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous. Returns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete. ```dts function preloadData(href: string): Promise< | { type: 'loaded'; status: number; data: Record; } | { type: 'redirect'; location: string; } >; ```
## 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). ```dts function pushState( url: string | URL, state: App.PageState ): void; ```
## 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). ```dts function replaceState( url: string | URL, state: App.PageState ): void; ```
# $app/paths
```js // @noErrors import { assets, base, resolveRoute } from '$app/paths'; ``` ## assets An absolute path that matches [`config.kit.paths.assets`](/docs/kit/configuration#paths). ```dts let assets: | '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; ```
## base A string that matches [`config.kit.paths.base`](/docs/kit/configuration#paths). Example usage: `Link` ```dts let base: '' | `/${string}`; ```
## resolveRoute Populate a route ID with params to resolve a pathname. ```js // @errors: 7031 import { resolveRoute } from '$app/paths'; resolveRoute( `/blog/[slug]/[...somethingElse]`, { slug: 'hello-world', somethingElse: 'something/else' } ); // `/blog/hello-world/something/else` ``` ```dts function resolveRoute( id: string, params: Record ): string; ```
# $app/server
```js // @noErrors import { read } from '$app/server'; ``` ## read Available since 2.4.0
Read the contents of an imported asset from the filesystem ```js // @errors: 7031 import { read } from '$app/server'; import somefile from './somefile.txt'; const asset = read(somefile); const text = await asset.text(); ``` ```dts function read(asset: string): Response; ```
# $app/state
SvelteKit makes three read-only state objects available via the `$app/state` module — `page`, `navigating` and `updated`. > 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; }; ```
# $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 // @noErrors import { getStores, navigating, page, updated } from '$app/stores'; ``` ## getStores ```dts function getStores(): { page: typeof page; navigating: typeof navigating; updated: typeof updated; }; ```
## 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`. On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time. ```dts const navigating: import('svelte/store').Readable< import('@sveltejs/kit').Navigation | null >; ```
## 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. ```dts const page: import('svelte/store').Readable< import('@sveltejs/kit').Page >; ```
## 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. ```dts const updated: import('svelte/store').Readable & { check(): Promise; }; ```
# $env/dynamic/private
This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](/docs/kit/cli)), this is equivalent to `process.env`. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](/docs/kit/configuration#env) (if configured). This module cannot be imported into client-side code. Dynamic environment variables cannot be used during prerendering. ```ts import { env } from '$env/dynamic/private'; console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE); ``` > In `dev`, `$env/dynamic` always includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter.
# $env/dynamic/public
Similar to [`$env/dynamic/private`](/docs/kit/$env-dynamic-private), but only includes variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. Note that public dynamic environment variables must all be sent from the server to the client, causing larger network requests — when possible, use `$env/static/public` instead. Dynamic environment variables cannot be used during prerendering. ```ts import { env } from '$env/dynamic/public'; console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE); ```
# $env/static/private
Environment variables [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env`. Like [`$env/dynamic/private`](/docs/kit/$env-dynamic-private), this module cannot be imported into client-side code. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](/docs/kit/configuration#env) (if configured). _Unlike_ [`$env/dynamic/private`](/docs/kit/$env-dynamic-private), the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination. ```ts import { API_KEY } from '$env/static/private'; ``` Note that all environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed: ``` MY_FEATURE_FLAG="" ``` You can override `.env` values from the command line like so: ```bash MY_FEATURE_FLAG="enabled" npm run dev ```
# $env/static/public
Similar to [`$env/static/private`](/docs/kit/$env-static-private), except that it only includes environment variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. Values are replaced statically at build time. ```ts import { PUBLIC_BASE_URL } from '$env/static/public'; ```
# $lib
SvelteKit automatically makes files under `src/lib` available using the `$lib` import alias. You can change which directory this alias points to in your [config file](configuration#files). ```svelte A reusable component ``` ```svelte ```
# $service-worker
```js // @noErrors import { base, build, files, prerendered, version } from '$service-worker'; ``` This module is only available to [service workers](/docs/kit/service-workers). ## base The `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory. Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified. ```dts const base: string; ```
## build An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`. During development, this is an empty array. ```dts const build: string[]; ```
## files An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](/docs/kit/configuration) ```dts const files: string[]; ```
## prerendered An array of pathnames corresponding to prerendered pages and endpoints. During development, this is an empty array. ```dts const prerendered: string[]; ```
## version See [`config.kit.version`](/docs/kit/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches. ```dts const version: string; ```
# Configuration
Your project's configuration lives in a `svelte.config.js` file at the root of your project. As well as SvelteKit, this config object is used by other tooling that integrates with Svelte such as editor extensions. ```js /// file: svelte.config.js // @filename: ambient.d.ts declare module '@sveltejs/adapter-auto' { const plugin: () => import('@sveltejs/kit').Adapter; export default plugin; } // @filename: index.js // ---cut--- import adapter from '@sveltejs/adapter-auto'; /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { adapter: adapter() } }; export default config; ``` ## Config ```dts interface Config {/*…*/} ```
```dts compilerOptions?: CompileOptions; ```
- default `{}`
Options passed to [`svelte.compile`](/docs/svelte/svelte-compiler#CompileOptions).
```dts extensions?: string[]; ```
- default `[".svelte"]`
List of file extensions that should be treated as Svelte files.
```dts kit?: KitConfig; ```
SvelteKit options
```dts preprocess?: any; ```
Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities.
```dts vitePlugin?: PluginOptions; ```
`vite-plugin-svelte` plugin options.
```dts [key: string]: any; ```
Any additional options required by tooling that integrates with Svelte.
## KitConfig The `kit` property configures SvelteKit, and can have the following properties: ## adapter - default `undefined`
Your [adapter](/docs/kit/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms.
## alias - default `{}`
An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript. ```js // @errors: 7031 /// file: svelte.config.js /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { alias: { // this will match a file 'my-file': 'path/to/my-file.js', // this will match a directory and its contents // (`my-directory/x` resolves to `path/to/my-directory/x`) 'my-directory': 'path/to/my-directory', // an alias ending /* will only match // the contents of a directory, not the directory itself 'my-directory/*': 'path/to/my-directory/*' } } }; ```
## appDir - default `"_app"`
The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes. If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`.
## csp
[Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this... ```js // @errors: 7031 /// file: svelte.config.js /** @type {import('@sveltejs/kit').Config} */ const config = { kit: { csp: { directives: { 'script-src': ['self'] }, // must be specified with either the `report-uri` or `report-to` directives, or both reportOnly: { 'script-src': ['self'], 'report-uri': ['/'] } } } }; export default config; ``` ...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates. To add a nonce for scripts and links manually included in `src/app.html`, you may use the placeholder `%sveltekit.nonce%` (for example ` ``` ## paths
```ts // @noErrors assets?: '' | `http://${string}` | `https://${string}`; ```
- default `""`
An absolute path that your app's files are served from. This is useful if your files are served from a storage bucket of some kind.
```ts // @noErrors base?: '' | `/${string}`; ```
- default `""`
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`](/docs/kit/$app-paths#base) for that: `
Link`. If you find yourself writing this often, it may make sense to extract this into a reusable component.
```ts // @noErrors relative?: boolean; ```
- default `true` - available since v1.9.0
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](/docs/kit/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. 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.
## prerender
See [Prerendering](/docs/kit/page-options#prerender). ```ts // @noErrors concurrency?: number; ```
- default `1`
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.
```ts // @noErrors crawl?: boolean; ```
- default `true`
Whether SvelteKit should find pages to prerender by following links from `entries`.
```ts // @noErrors entries?: Array<'*' | `/${string}`>; ```
- default `["*"]`
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).
```ts // @noErrors handleHttpError?: PrerenderHttpErrorHandlerValue; ```
- default `"fail"` - available since v1.15.7
How to respond to HTTP errors encountered while prerendering the app. - `'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); } } } }; ```
```ts // @noErrors handleMissingId?: PrerenderMissingIdHandlerValue; ```
- default `"fail"` - available since v1.15.7
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
```ts // @noErrors handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue; ```
- default `"fail"` - available since v1.16.0
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
```ts // @noErrors origin?: string; ```
- default `"http://sveltekit-prerender"`
The value of `url.origin` during prerendering; useful if it is included in rendered content.
## router
```ts // @noErrors type?: 'pathname' | 'hash'; ```
- default `"pathname"` - available since v2.14.0
What type of client-side router to use. - `'pathname'` is the default and means the current URL pathname determines the route - `'hash'` means the route is determined by `location.hash`. In this case, SSR and prerendering are disabled. This is only recommended if `pathname` is not an option, for example because you don't control the webserver where your app is deployed. It comes with some caveats: you can't use server-side rendering (or indeed any server logic), and you have to make sure that the links in your app all start with #/, or they won't work. Beyond that, everything works exactly like a normal SvelteKit app.
## serviceWorker
```ts // @noErrors register?: boolean; ```
- default `true`
Whether to automatically register the service worker, if it exists.
```ts // @noErrors files?(filepath: string): boolean; ```
- default `(filename) => !/\.DS_Store/.test(filename)`
Determine which files in your `static` directory will be available in `$service-worker.files`.
## typescript
```ts // @noErrors config?: (config: Record
) => Record | void; ``` - default `(config) => config` - available since v1.3.0
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.
## version
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 ``` If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of [`updated.current`](/docs/kit/$app-state#updated) `true` when it detects one. ```ts // @noErrors name?: string; ```
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. For example, to use the current commit hash, you could do use `git rev-parse HEAD`: ```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() } } }; ```
```ts // @noErrors pollInterval?: number; ```
- default `0`
The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs.
# Command Line Interface
SvelteKit projects use [Vite](https://vitejs.dev), meaning you'll mostly use its CLI (albeit via `npm run dev/build/preview` scripts): - `vite dev` — start a development server - `vite build` — build a production version of your app - `vite preview` — run the production version locally However SvelteKit includes its own CLI for initialising your project: ## svelte-kit sync `svelte-kit sync` creates the `tsconfig.json` and all generated types (which you can import as `./$types` inside routing files) for your project. When you create a new project, it is listed as the `prepare` script and will be run automatically as part of the npm lifecycle, so you should not ordinarily have to run this command.
# Types
## Generated types The `RequestHandler` and `Load` types both accept a `Params` argument allowing you to type the `params` object. For example this endpoint expects `foo`, `bar` and `baz` params: ```js /// file: src/routes/[foo]/[bar]/[baz]/+page.server.js // @errors: 2355 2322 1360 /** @type {import('@sveltejs/kit').RequestHandler<{ foo: string; bar: string; baz: string }>} */ export async function GET({ params }) { // ... } ``` Needless to say, this is cumbersome to write out, and less portable (if you were to rename the `[foo]` directory to `[qux]`, the type would no longer reflect reality). To solve this problem, SvelteKit generates `.d.ts` files for each of your endpoints and pages: ```ts /// file: .svelte-kit/types/src/routes/[foo]/[bar]/[baz]/$types.d.ts /// link: true import type * as Kit from '@sveltejs/kit'; type RouteParams = { foo: string; bar: string; baz: string; }; export type PageServerLoad = Kit.ServerLoad; export type PageLoad = Kit.Load; ``` These files can be imported into your endpoints and pages as siblings, thanks to the [`rootDirs`](https://www.typescriptlang.org/tsconfig#rootDirs) option in your TypeScript configuration: ```js /// file: src/routes/[foo]/[bar]/[baz]/+page.server.js // @filename: $types.d.ts import type * as Kit from '@sveltejs/kit'; type RouteParams = { foo: string; bar: string; baz: string; } export type PageServerLoad = Kit.ServerLoad; // @filename: index.js // @errors: 2355 // ---cut--- /** @type {import('./$types').PageServerLoad} */ export async function GET({ params }) { // ... } ``` ```js /// file: src/routes/[foo]/[bar]/[baz]/+page.js // @filename: $types.d.ts import type * as Kit from '@sveltejs/kit'; type RouteParams = { foo: string; bar: string; baz: string; } export type PageLoad = Kit.Load; // @filename: index.js // @errors: 2355 // ---cut--- /** @type {import('./$types').PageLoad} */ export async function load({ params, fetch }) { // ... } ``` The return types of the load functions are then available through the `$types` module as `PageData` and `LayoutData` respectively, while the union of the return values of all `Actions` is available as `ActionData`. Starting with version 2.16.0, two additional helper types are provided. `PageProps` defines `data: PageData`, as well as `form: ActionData`, when there are actions defined. `LayoutProps` defines `data: LayoutData`, as well as `children: Snippet`: ```svelte ``` > Before 2.16.0: > ```svelte > > > ``` > > Using Svelte 4: > ```svelte > > > ``` > > `{ "extends": "./.svelte-kit/tsconfig.json" }` ### Default tsconfig.json The generated `.svelte-kit/tsconfig.json` file contains a mixture of options. Some are generated programmatically based on your project configuration, and should generally not be overridden without good reason: ```json /// file: .svelte-kit/tsconfig.json { "compilerOptions": { "baseUrl": "..", "paths": { "$lib": "src/lib", "$lib/*": "src/lib/*" }, "rootDirs": ["..", "./types"] }, "include": ["../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte"], "exclude": ["../node_modules/**", "./**"] } ``` Others are required for SvelteKit to work properly, and should also be left untouched unless you know what you're doing: ```json /// file: .svelte-kit/tsconfig.json { "compilerOptions": { // this ensures that types are explicitly // imported with `import type`, which is // necessary as svelte-preprocess cannot // otherwise compile components correctly "importsNotUsedAsValues": "error", // Vite compiles one TypeScript module // at a time, rather than compiling // the entire module graph "isolatedModules": true, // TypeScript cannot 'see' when you // use an imported value in your // markup, so we need this "preserveValueImports": true, // This ensures both `vite build` // and `svelte-package` work correctly "lib": ["esnext", "DOM", "DOM.Iterable"], "moduleResolution": "node", "module": "esnext", "target": "esnext" } } ``` ## $lib This is a simple alias to `src/lib`, or whatever directory is specified as [`config.kit.files.lib`](configuration#files). It allows you to access common components and utility modules without `../../../../` nonsense. ### $lib/server A subdirectory of `$lib`. SvelteKit will prevent you from importing any modules in `$lib/server` into client-side code. See [server-only modules](server-only-modules). ## app.d.ts The `app.d.ts` file is home to the ambient types of your apps, i.e. types that are available without explicitly importing them. Always part of this file is the `App` namespace. This namespace contains several types that influence the shape of certain SvelteKit features you interact with. ## Error Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape. ```dts interface Error {/*…*/} ```
```dts message: string; ```
## Locals The interface that defines `event.locals`, which can be accessed in server [hooks](/docs/kit/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files. ```dts interface Locals {} ```
## PageData Defines the common shape of the [page.data state](/docs/kit/$app-state#page) and [$page.data store](/docs/kit/$app-stores#page) - that is, the data that is shared between all pages. The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly. Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`). ```dts interface PageData {} ```
## PageState The shape of the `page.state` object, which can be manipulated using the [`pushState`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`. ```dts interface PageState {} ```
## Platform If your adapter provides [platform-specific context](/docs/kit/adapters#Platform-specific-context) via `event.platform`, you can specify it here. ```dts interface Platform {} ```
# Start of the Svelte CLI documentation
# Overview
コマンドラインインターフェイス(CLI)である`sv`は、Svelteアプリケーションの作成と管理のためのツールキットです。 ## 使用方法 `sv`を実行する最も簡単な方法は、[`npx`](https://docs.npmjs.com/cli/v8/commands/npx)(または他のパッケージマネージャを使用している場合は同等のコマンド - 例えば、[pnpm](https://pnpm.io/)を使用している場合は`pnpx`)を使うことです: ```bash npx sv ``` 既に`sv`がインストールされているプロジェクトの内部にいる場合は、ローカルインストールを使用します。それ以外の場合は最新バージョンをダウンロードしてインストール無しで実行します。これは特に[`sv create`](sv-create)に便利です。 ## 謝辞 npmで元々`sv`という名前を所有していた[Christopher Brown](https://github.com/chbrown)に感謝いたします。彼のおかげで、この名前がSvelte CLIのために使えるようになりました。元の`sv`パッケージは[`@chbrown/sv`](https://www.npmjs.com/package/@chbrown/sv)で見つけることができます。
# sv create
`sv create`は、[追加機能の設定](sv-add#Official-add-ons)オプションを含む新しいSvelteKitプロジェクトをセットアップします。 ## 使用方法 ```bash npx sv create [options] [path] ``` ## オプション ### `--template ` 使用するプロジェクトテンプレート: - `minimal` — 新しいアプリのための最小限のスキャフォールディング - `demo` — JavaScript無しで動作するワードパズルゲームを備えたデモアプリ - `library` — Svelteライブラリのためのテンプレートで、`svelte-package`でセットアップされています ### `--types