`。 ### 网站地图 [网站地图](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 现代网页开发的一个不幸现实是,有时有必要创建一个[加速移动页面(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; ``` ...在您的根目录 `csr` 中禁用 `+layout.js`/`+layout.server.js`... ```js /// file: src/routes/+layout.server.js export const csr = false; ``` ...将`amp`添加到您的`app.html`中 `<html amp> ...` ...并使用 `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}`); } } }); } ``` > \[!注意\] 使用 `handle` 钩子来验证转换后的 HTML 使用 `amphtml-validator` 是一个好主意,但仅当你在预渲染页面时,因为它非常慢。
# @sveltejs/kit
```js // @noErrors import { Server, VERSION, error, fail, isActionFailure, isHttpError, isRedirect, json, normalizeUrl, 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. Call when form submission fails. ```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; ```
## normalizeUrl Available since 2.18.0 Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname. Returns the normalized URL as well as a method for adding the potential suffix back based on a new pathname (possibly including search) or URL. ```js // @errors: 7031 import { normalizeUrl } from '@sveltejs/kit'; const { url, denormalize } = normalizeUrl('/blog/post/__data.json'); console.log(url.pathname); // /blog/post console.log(denormalize('/blog/post/a')); // /blog/post/a/__data.json ``` ```dts function normalizeUrl(url: URL | string): { url: URL; wasNormalized: boolean; denormalize: (url?: string | URL) => URL; }; ```
## 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 ` 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`](/docs/kit/$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`](/docs/kit/$app-state#page) reactive object and the [`$page`](/docs/kit/$app-stores) 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]`. It is `null` when no route is matched.
```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`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.
```dts form: any; ```
Filled only after a form submission. See [form actions](/docs/kit/form-actions) for more info.
## ParamMatcher The shape of a param matcher. See [matching](/docs/kit/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`](/docs/kit/@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`](/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](/docs/kit/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 [`server handle hook`](/docs/kit/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]`. It is `null` when no route is matched.
```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(); } ``` 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`](/docs/kit/@sveltejs-kit#Cookies) API instead.
```dts url: URL; ```
The requested URL.
```dts isDataRequest: boolean; ```
`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.
```dts isSubRequest: boolean; ```
`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](/docs/kit/types#Generated-types) instead. ```dts type RequestHandler< Params extends Partial
> = Partial< Record >, RouteId extends string | null = string | null > = ( event: RequestEvent ) => MaybePromise; ``` ## 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. ```dts type Reroute = (event: { url: URL; fetch: typeof fetch; }) => MaybePromise; ```
## ResolveOptions ```dts interface ResolveOptions {/*…*/} ```
```dts transformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise
; ``` - `input` the html chunk and the info if this is the last chunk
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 filterSerializedResponseHeaders?: (name: string, value: string) => boolean; ```
- `name` header name - `value` header value
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 preload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean; ```
- `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.
## RouteDefinition ```dts interface RouteDefinition
{/*…*/} ``` ```dts api: { methods: Array
; }; ```
```dts page: { methods: Array
>; }; ```
```dts pattern: RegExp; ```
```dts prerender: PrerenderOption; ```
```dts segments: RouteSegment[]; ```
```dts methods: Array
; ```
```dts config: Config; ```
## SSRManifest ```dts interface SSRManifest {/*…*/} ```
```dts appDir: string; ```
```dts appPath: string; ```
```dts assets: Set
; ``` Static files from `kit.config.files.assets` and the service worker (if any).
```dts mimeTypes: Record
; ```
```dts _: {/*…*/} ```
private fields
```dts client: NonNullable
; ```
```dts nodes: SSRNodeLoader[]; ```
```dts routes: SSRRoute[]; ```
```dts prerendered_routes: Set
; ```
```dts matchers: () => Promise
>; ```
```dts server_assets: Record
; ``` A `[file]: size` map of all assets imported by server code.
## ServerInit Available since 2.10.0 The [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked before the server responds to its first request ```dts type ServerInit = () => MaybePromise; ```
## ServerInitOptions ```dts interface ServerInitOptions {/*…*/} ```
```dts env: Record
; ``` A map of environment variables.
```dts read?: (file: string) => MaybePromise
; ``` 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](/docs/kit/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 parent: () => Promise
; ``` `await parent()` returns data from parent `+layout.server.js` `load` functions. 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.
```dts 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()`](/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`. 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: 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}
Increase 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.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
{/*…*/} ``` ```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; }) => MaybePromise) >; ```
## 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 The following are referenced by the public types documented above, but cannot be imported directly: ## AdapterEntry ```dts interface AdapterEntry {/*…*/} ```
```dts id: string; ```
A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication. For example, `/foo/a-[b]` and `/foo/[c]` are different routes, but would both be represented in a Netlify _redirects file as `/foo/:param`, so they share an ID
```dts filter(route: RouteDefinition): boolean; ```
A function that compares the candidate route with the current route to determine if it should be grouped with the current route. Use cases: - Fallback pages: `/foo/[c]` is a fallback for `/foo/a-[b]`, and `/[...catchall]` is a fallback for all routes - Grouping routes that share a common `config`: `/foo` should be deployed to the edge, `/bar` and `/baz` should be deployed to a serverless function
```dts complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise
; ``` A function that is invoked once the entry has been created. This is where you should write the function to the filesystem and generate redirect manifests.
## Csp ```dts namespace Csp { type ActionSource = 'strict-dynamic' | 'report-sample'; type BaseSource = | 'self' | 'unsafe-eval' | 'unsafe-hashes' | 'unsafe-inline' | 'wasm-unsafe-eval' | 'none'; type CryptoSource = `${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`; type FrameSource = | HostSource | SchemeSource | 'self' | 'none'; type HostNameScheme = `${string}.${string}` | 'localhost'; type HostSource = `${HostProtocolSchemes}${HostNameScheme}${PortScheme}`; type HostProtocolSchemes = `${string}://` | ''; type HttpDelineator = '/' | '?' | '#' | '\\'; type PortScheme = `:${number}` | '' | ':*'; type SchemeSource = | 'http:' | 'https:' | 'data:' | 'mediastream:' | 'blob:' | 'filesystem:'; type Source = | HostSource | SchemeSource | CryptoSource | BaseSource; type Sources = Source[]; } ```
## CspDirectives ```dts interface CspDirectives {/*…*/} ```
```dts 'child-src'?: Csp.Sources; ```
```dts 'default-src'?: Array
; ```
```dts 'frame-src'?: Csp.Sources; ```
```dts 'worker-src'?: Csp.Sources; ```
```dts 'connect-src'?: Csp.Sources; ```
```dts 'font-src'?: Csp.Sources; ```
```dts 'img-src'?: Csp.Sources; ```
```dts 'manifest-src'?: Csp.Sources; ```
```dts 'media-src'?: Csp.Sources; ```
```dts 'object-src'?: Csp.Sources; ```
```dts 'prefetch-src'?: Csp.Sources; ```
```dts 'script-src'?: Array
; ```
```dts 'script-src-elem'?: Csp.Sources; ```
```dts 'script-src-attr'?: Csp.Sources; ```
```dts 'style-src'?: Array
; ```
```dts 'style-src-elem'?: Csp.Sources; ```
```dts 'style-src-attr'?: Csp.Sources; ```
```dts 'base-uri'?: Array
; ```
```dts sandbox?: Array< | 'allow-downloads-without-user-activation' | 'allow-forms' | 'allow-modals' | 'allow-orientation-lock' | 'allow-pointer-lock' | 'allow-popups' | 'allow-popups-to-escape-sandbox' | 'allow-presentation' | 'allow-same-origin' | 'allow-scripts' | 'allow-storage-access-by-user-activation' | 'allow-top-navigation' | 'allow-top-navigation-by-user-activation' >; ```
```dts 'form-action'?: Array
; ```
```dts 'frame-ancestors'?: Array
; ```
```dts 'navigate-to'?: Array
; ```
```dts 'report-uri'?: string[]; ```
```dts 'report-to'?: string[]; ```
```dts 'require-trusted-types-for'?: Array<'script'>; ```
```dts 'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>; ```
```dts 'upgrade-insecure-requests'?: boolean; ```
```dts 'require-sri-for'?: Array<'script' | 'style' | 'script style'>; ```
```dts 'block-all-mixed-content'?: boolean; ```
```dts 'plugin-types'?: Array<`${string}/${string}` | 'none'>; ```
```dts referrer?: Array< | 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url' | 'none' >; ```
## HttpMethod ```dts type HttpMethod = | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS'; ```
## Logger ```dts interface Logger {/*…*/} ```
```dts (msg: string): void; ```
```dts success(msg: string): void; ```
```dts error(msg: string): void; ```
```dts warn(msg: string): void; ```
```dts minor(msg: string): void; ```
```dts info(msg: string): void; ```
## MaybePromise ```dts type MaybePromise = T | Promise; ```
## PrerenderEntryGeneratorMismatchHandler ```dts interface PrerenderEntryGeneratorMismatchHandler {/*…*/} ```
```dts (details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void; ```
## PrerenderEntryGeneratorMismatchHandlerValue ```dts type PrerenderEntryGeneratorMismatchHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderEntryGeneratorMismatchHandler; ```
## PrerenderHttpErrorHandler ```dts interface PrerenderHttpErrorHandler {/*…*/} ```
```dts (details: { status: number; path: string; referrer: string | null; referenceType: 'linked' | 'fetched'; message: string; }): void; ```
## PrerenderHttpErrorHandlerValue ```dts type PrerenderHttpErrorHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderHttpErrorHandler; ```
## PrerenderMap ```dts type PrerenderMap = Map; ```
## PrerenderMissingIdHandler ```dts interface PrerenderMissingIdHandler {/*…*/} ```
```dts (details: { path: string; id: string; referrers: string[]; message: string }): void; ```
## PrerenderMissingIdHandlerValue ```dts type PrerenderMissingIdHandlerValue = | 'fail' | 'warn' | 'ignore' | PrerenderMissingIdHandler; ```
## PrerenderOption ```dts type PrerenderOption = boolean | 'auto'; ```
## Prerendered ```dts interface Prerendered {/*…*/} ```
```dts pages: Map< string, { /** The location of the .html file relative to the output directory */ file: string; } >; ```
A map of `path` to `{ file }` objects, where a path like `/foo` corresponds to `foo.html` and a path like `/bar/` corresponds to `bar/index.html`.
```dts assets: Map< string, { /** The MIME type of the asset */ type: string; } >; ```
A map of `path` to `{ type }` objects.
```dts redirects: Map< string, { status: number; location: string; } >; ```
A map of redirects encountered during prerendering.
```dts paths: string[]; ```
An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
## RequestOptions ```dts interface RequestOptions {/*…*/} ```
```dts getClientAddress(): string; ```
```dts platform?: App.Platform; ```
## RouteSegment ```dts interface RouteSegment {/*…*/} ```
```dts content: string; ```
```dts dynamic: boolean; ```
```dts rest: boolean; ```
## TrailingSlash ```dts type TrailingSlash = 'never' | 'always' | 'ignore'; ```
# @sveltejs/kit/hooks
```js // @noErrors import { sequence } from '@sveltejs/kit/hooks'; ``` ## sequence A helper function for sequencing multiple `handle` calls in a middleware-like manner. The behavior for the `handle` options is as follows: - `transformPageChunk` is applied in reverse order and merged - `preload` is applied in forward order, the first option "wins" and no `preload` options after it are called - `filterSerializedResponseHeaders` behaves the same as `preload` ```js // @errors: 7031 /// file: src/hooks.server.js import { sequence } from '@sveltejs/kit/hooks'; /** @type {import('@sveltejs/kit').Handle} */ async function first({ event, resolve }) { console.log('first pre-processing'); const result = await resolve(event, { transformPageChunk: ({ html }) => { // transforms are applied in reverse order console.log('first transform'); return html; }, preload: () => { // this one wins as it's the first defined in the chain console.log('first preload'); return true; } }); console.log('first post-processing'); return result; } /** @type {import('@sveltejs/kit').Handle} */ async function second({ event, resolve }) { console.log('second pre-processing'); const result = await resolve(event, { transformPageChunk: ({ html }) => { console.log('second transform'); return html; }, preload: () => { console.log('second preload'); return true; }, filterSerializedResponseHeaders: () => { // this one wins as it's the first defined in the chain console.log('second filterSerializedResponseHeaders'); return true; } }); console.log('second post-processing'); return result; } export const handle = sequence(first, second); ``` The example above would print: ``` first pre-processing first preload second pre-processing second filterSerializedResponseHeaders second transform first transform second post-processing first post-processing ``` ```dts function sequence( ...handlers: import('@sveltejs/kit').Handle[] ): import('@sveltejs/kit').Handle; ```
# @sveltejs/kit/node/polyfills
```js // @noErrors import { installPolyfills } from '@sveltejs/kit/node/polyfills'; ``` ## installPolyfills Make various web APIs available as globals: - `crypto` - `File` ```dts function installPolyfills(): void; ```
# @sveltejs/kit/node
```js // @noErrors import { createReadableStream, getRequest, setResponse } from '@sveltejs/kit/node'; ``` ## createReadableStream Available since 2.4.0 Converts a file on disk to a readable stream ```dts function createReadableStream(file: string): ReadableStream; ```
## getRequest ```dts function getRequest({ request, base, bodySizeLimit }: { request: import('http').IncomingMessage; base: string; bodySizeLimit?: number; }): Promise; ```
## setResponse ```dts function setResponse( res: import('http').ServerResponse, response: Response ): Promise; ```
# @sveltejs/kit/vite
```js // @noErrors import { sveltekit } from '@sveltejs/kit/vite'; ``` ## sveltekit Returns the SvelteKit Vite plugins. ```dts function sveltekit(): Promise; ```
# $app/environment
```js // @noErrors import { browser, building, dev, version } from '$app/environment'; ``` ## 浏览器 `如果应用程序在浏览器中运行。` `const 浏览器: boolean;` ## 建筑 SvelteKit 在构建步骤中通过运行它来分析您的应用程序。在这个过程中,`构建`是`正在进行的`,`true`。这也适用于预渲染期间。 ```dts const building: boolean; ``` ## dev 是否开发服务器正在运行。这并不保证与 `NODE_ENV` 或 `MODE` 相对应。 ```dts const dev: boolean; ``` ## 版本 值 of `config.kit.version.name`. `const 版本:string;`
# $app/forms
```js // @noErrors import { applyAction, deserialize, enhance } from '$app/forms'; ``` ## 应用动作 此操作使用给定数据更新当前页面的 `表单` 属性和更新 `page.status`。如果发生错误,将重定向到最近的错误页面。 ```dts function applyAction< Success extends Record | undefined, Failure extends Record | undefined >( result: import('@sveltejs/kit').ActionResult< Success, Failure > ): Promise; ``` ## 反序列化 使用此函数反序列化表单提交的响应。用法: ```js // @errors: 7031 import { deserialize } from '$app/forms'; async function handleSubmit(event) { const response = await fetch('/form?/action', { method: 'POST', body: new FormData(event.target) }); const result = deserialize(await response.text()); // ... } ``` ```dts function deserialize< Success extends Record | undefined, Failure extends Record | undefined >( result: string ): import('@sveltejs/kit').ActionResult; ``` ## 增强 此操作增强了一个``元素,否则该元素在没有 JavaScript 的情况下也能正常工作。 提交时,将使用给定的 FormData 和应触发的`action`调用`submit`函数。如果调用`cancel`,则表单将不会提交。如果另一个开始,可以使用 abort `controller`取消提交。如果返回一个函数,则该函数将使用来自服务器的响应被调用。如果没有返回任何内容,将使用回退方案。 如果此函数或其返回值未设置,则 * 回退到更新同一页面上表单的 `prop`,如果操作在该表单页面上 * 更新 `page.status` * 重置 ` ` 元素,并在无重定向响应的成功提交情况下使所有数据无效 * 重定向情况下的重定向响应 * 重定向到最近的错误页面,以处理意外错误 如果您提供了一个带有回调的自定义函数并希望使用默认行为,请在您的回调中调用`update`。它接受一个选项对象 * `重置:否`如果您不希望在成功提交后重置 ` ` 的值 * `invalidateAll: false` 如果您不想在提交后调用 `invalidateAll` ```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 一个在当前组件挂载时运行提供的 `回调` 的生命周期函数,并且每次我们导航到 URL 时也会运行。 `afterNavigate` 必须在组件初始化期间调用。只要组件挂载,它就保持激活状态。 ```dts function afterNavigate( callback: ( navigation: import('@sveltejs/kit').AfterNavigate ) => void ): void; ``` ## 在导航之前 一个在我们导航到 URL 之前触发的导航拦截器,无论是通过点击链接、调用`goto(...)`,还是使用浏览器的后退/前进控件。 调用 `cancel()` 将阻止导航完成。如果 `navigation.type === 'leave'` —— 表示用户正在离开应用(或关闭标签页)—— 调用 `cancel` 将触发原生的浏览器卸载确认对话框。在这种情况下,导航可能会取消,也可能不会取消,具体取决于用户的响应。 當導航不是指向 SvelteKit 擁有的路徑(因此由 SvelteKit 的客戶端路由器控制)時,`navigation.to.route.id`將會是`null`。 如果导航(如果没有取消)会导致文档卸载——换句话说,`'离开'`导航和`'链接'`导航,其中`navigation.to.route === null`——则`navigation.willUnload`为`true`。 `beforeNavigate` 必须在组件初始化期间调用。只要组件挂载,它就保持激活状态。 ```dts function beforeNavigate( callback: ( navigation: import('@sveltejs/kit').BeforeNavigate ) => void ): void; ``` ## 禁用滚动处理 如果页面在导航后更新时被调用(在`onMount`或`afterNavigate`或执行某个操作时,例如),这将禁用 SvelteKit 的内置滚动处理。这通常是不被推荐的,因为它会打破用户的期望。 ```dts function disableScrollHandling(): void; ``` ## 转到 允许您以编程方式导航到指定路由,包括保持当前元素聚焦等选项。返回一个当 SvelteKit 导航(或未能导航,此时承诺拒绝)到指定 `url` 时解决的 Promise。 对于外部 URL,请使用`window.location = url`代替调用`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; ``` ## 无效 导致属于当前活动页面的任何`加载`函数在它们依赖于所涉及的问题`URL`的情况下重新运行,通过`fetch`或`depends`。当页面随后更新时,返回一个`Promise`,该 Promise 将解决。 如果参数以`字符串`或`URL`的形式给出,它必须解析为传递给`fetch`或`depends`(包括查询参数)的相同 URL。要创建自定义标识符,请使用以`[a-z]+:`(例如`custom:state`)开头的字符串——这是一个有效的 URL。 The `function` argument can be used to 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 an 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; ``` ## 无效所有 导致当前活动页面中属于所有 `load` 函数重新运行。返回一个在页面随后更新时解决的 `Promise`。 ```dts function invalidateAll(): Promise; ``` ## 在导航中 一个在导航到新 URL 之前立即运行提供的`回调`的生命周期函数,除了在整页导航期间。 如果您返回一个 `Promise`,SvelteKit 将在完成导航之前等待其解析。这允许您——例如——使用 `document.startViewTransition`。避免解析缓慢的承诺,因为导航将看起来对用户停滞不前。 如果从回调中返回一个函数(或一个解析为函数的 `Promise`),则将在 DOM 更新后调用该函数。 `onNavigate`必须在组件初始化期间调用。只要组件挂载,它就保持激活状态。 ```dts function onNavigate( callback: ( navigation: import('@sveltejs/kit').OnNavigate ) => MaybePromise<(() => void) | void> ): void; ``` ## 预加载代码 程序化导入尚未获取的路由代码。通常,您可能会调用此功能以加快后续导航。 您可以通过任何匹配的路径名来指定路由,例如 `/about`(以匹配 `src/routes/about/+page.svelte`)或 `/blog/*`(以匹配 `src/routes/blog/[slug]/+page.svelte` )。 不同于 `preloadData`,这不会调用 `load` 函数。返回一个在模块导入完成后解决的 Promise。 ```dts function preloadCode(pathname: string): Promise; ``` ## 预载数据 程序预加载指定页面,即 1. 确保页面代码已加载, 2. 调用页面加载函数,使用适当的选项。 这是 SvelteKit 在用户点击或鼠标悬停在具有``元素和`data-sveltekit-preload-data`的情况下触发的相同行为。如果下一次导航到`href`,将使用加载返回的值,使导航瞬间完成。在预加载完成后,返回一个解析为新路由`load`函数运行结果的 Promise。 ```dts function preloadData(href: string): Promise< | { type: 'loaded'; status: number; data: Record; } | { type: 'redirect'; location: string; } >; ``` ## pushState 程序创建一个新的历史条目,使用给定的 `page.state`。要使用当前 URL,可以将`''`作为第一个参数传递。用于[浅层路由](/docs/kit/shallow-routing)。 ```dts function pushState( url: string | URL, state: App.PageState ): void; ``` ## 替换状态 程序替换当前历史条目为给定的 `page.state`。要使用当前 URL,可以将 `''` 作为第一个参数传递。用于 [浅层路由](/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'; ``` ## 资产 绝对路径匹配 [`config.kit.paths.assets`](/docs/kit/configuration#paths)。 > \[注意\] 如果指定了 `config.kit.paths.assets` 的值,则在 `vite dev` 或 `vite preview` 期间,它将被 `'/_svelte_kit_assets'` 替换,因为资产尚未位于其最终 URL。 ```dts let assets: | '' | `https://${string}` | `http://${string}` | '/_svelte_kit_assets'; ``` ## 基础 一个匹配[`config.kit.paths.base`](/docs/kit/configuration#paths)的字符串。 示例用法: `Link ` ``let base: '' | `/${字符串}`;`` ## 解决路由 填充路由 ID 以解析路径名。 ```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 { getRequestEvent, read } from '$app/server'; ``` ## getRequestEvent > 自 2.20.0 起可用 返回当前 `RequestEvent`。可在服务器钩子、服务器 `load` 函数、操作和端点(以及由它们调用的函数)中使用。 在无`AsyncLocalStorage`的环境下,必须同步调用(即不在`await`之后)。 ```dts function getRequestEvent(): RequestEvent< Partial>, string | null >; ``` ## 读取 > 自 2.4.0 版本起可用 读取导入资产的文件系统内容 ```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 通过`$app/state`模块提供三个只读状态对象 —— `page`、`navigating`和`updated`。 > \[注意\] 此模块添加于 2.12 版本。如果您使用的是 SvelteKit 的早期版本,请使用[`$app/stores`]($app-stores)代替。 ```js // @noErrors import { navigating, page, updated } from '$app/state'; ``` ## 导航 一个表示正在进行的导航的只读对象,具有 `from`、`to`、`type` 以及(如果 `type === 'popstate'`)`delta` 属性。当没有导航发生或服务器渲染期间,值 `null`。 ```dts const navigating: | import('@sveltejs/kit').Navigation | { from: null; to: null; type: null; willUnload: null; delta: null; complete: null; }; ``` ## 页 一个只读的响应式对象,包含有关当前页面的信息,服务于多个用例: * 检索组件树中所有页面/布局的合并`数据`(也见[加载数据](/docs/kit/load)) * 检索组件树中任何位置的 `表单` 属性的当前值(也参见 [表单操作](/docs/kit/form-actions)) * 获取通过 `goto`、`pushState` 或 `replaceState` 设置的页面状态(也参见 [goto](/docs/kit/$app-navigation#goto) 和 [浅层路由](/docs/kit/shallow-routing)) * 检索元数据,例如您所在的 URL、当前路由及其参数,以及是否发生错误 ```svelte Currently at {page.url.pathname}
{#if page.error} Problem detected {:else} All systems operational {/if} ``` 变更 `页面` 仅可通过符文进行。 (旧的反应性语法将不会反映任何变更) ```svelte ``` 在服务器上,值只能在渲染时读取(换句话说,在例如 `加载` 函数中 *不能* 读取)。在浏览器中,值可以在任何时候读取。 ```dts const page: import('@sveltejs/kit').Page; ``` ## 更新 一个初始值为`false`的只读响应式值。如果`version.pollInterval`是一个非零值,SvelteKit 将轮询应用的新版本,并在检测到新版本时将`current`更新为`true`。`updated.check()`将强制立即检查,无论是否轮询。 ```dts const updated: { get current(): boolean; check(): Promise; }; ```
# $app/stores
此模块包含了对从 [`$app/state`]($app-state) 导出的基于存储的等效项。如果您正在使用 SvelteKit 2.12 或更高版本,请使用该模块。 ```js // @noErrors import { getStores, navigating, page, updated } from '$app/stores'; ``` ## 获取商店 ```dts function getStores(): { page: typeof page; navigating: typeof navigating; updated: typeof updated; }; ``` ## 导航 > 使用从 `$app/state` 的 `navigating` 替代(需要 Svelte 5,[查看文档以获取更多信息](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)) 可读的存储。当开始导航时,其值是一个具有 `Navigation` 对象,包含 `from`、`to`、`type` 和(如果 `type === 'popstate'`)`delta` 属性的 `null`。当导航完成时,其值恢复为 `null`。 在服务器上,此存储只能在组件初始化期间订阅。在浏览器中,可以在任何时候订阅。 ```dts const navigating: import('svelte/store').Readable< import('@sveltejs/kit').Navigation | null >; ``` ## 页 > 使用 `页面` 从 `$app/state` 中代替(需要 Svelte 5,[查看文档获取更多信息](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)) 一个包含页面数据的可读存储。 在服务器上,此存储只能在组件初始化期间订阅。在浏览器中,可以在任何时候订阅。 ```dts const page: import('svelte/store').Readable< import('@sveltejs/kit').Page >; ``` ## 更新 > 使用 `updated` 从 `$app/state` 中替换(需要 Svelte 5,[查看文档获取更多信息](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)) 一个初始值为`false`的可读存储。如果`version.pollInterval`是一个非零值,SvelteKit 将轮询应用的新版本,并在检测到新版本时将存储值更新为`true`。`updated.check()`将强制立即检查,无论是否轮询。 在服务器上,此存储只能在组件初始化期间订阅。在浏览器中,可以在任何时候订阅。 ```dts const updated: import('svelte/store').Readable & { check(): Promise; }; ```
# $env/dynamic/private
此模块提供对运行时环境变量的访问,这些变量由您运行的平台定义。例如,如果您正在使用[`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node)(或运行[`vite preview`](/docs/kit/cli)),则这相当于`process.env`。此模块仅包括不以[`config.kit.env.publicPrefix`](/docs/kit/configuration#env)开头且以[`config.kit.env.privatePrefix`](/docs/kit/configuration#env)开头(如果已配置)的变量。 此模块无法导入客户端代码。 动态环境变量在预渲染期间无法使用。 ```ts import { env } from '$env/dynamic/private'; console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE); ``` > 在`dev`中,`$env/dynamic`始终包含来自`.env`的环境变量。在`prod`中,此行为将取决于您的适配器。
# $env/dynamic/public
与[`$env/dynamic/private`](/docs/kit/$env-dynamic-private)类似,但仅包括以[`config.kit.env.publicPrefix`](/docs/kit/configuration#env)(默认为`PUBLIC_`)开头的变量,因此可以安全地暴露给客户端代码。 请注意,所有公共动态环境变量都必须从服务器发送到客户端,这会导致更大的网络请求——当可能时,请使用 `$env/static/public` 代替。 动态环境变量在预渲染期间无法使用。 ```ts import { env } from '$env/dynamic/public'; console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE); ```
# $env/static/private
环境变量由 Vite 加载的 [从](https://vitejs.dev/guide/env-and-mode.html#env-files) `.env` 文件和 `process.env` 中,类似于 [`$env/dynamic/private`](/docs/kit/$env-dynamic-private),此模块不能导入到客户端代码中。此模块仅包括不以 *不* 以 [`config.kit.env.publicPrefix`](/docs/kit/configuration#env)*和* 以 [`config.kit.env.privatePrefix`](/docs/kit/configuration#env)(如果已配置)开头的变量。 与*不同于*[`$env/dynamic/private`](/docs/kit/$env-dynamic-private)不同,此模块导出的值在构建时静态注入到您的包中,从而启用诸如死代码消除等优化。 ```ts import { API_KEY } from '$env/static/private'; ``` 请注意,您代码中引用的所有环境变量都应声明(例如在 `.env` 文件中),即使它们在应用部署之前没有值: ``` MY_FEATURE_FLAG="" ``` 您可以通过命令行像这样覆盖`.env`的值: ```bash MY_FEATURE_FLAG="enabled" npm run dev ```
# $env/static/public
与[`$env/static/private`](/docs/kit/$env-static-private)类似,但仅包括以[`config.kit.env.publicPrefix`](/docs/kit/configuration#env)(默认为`PUBLIC_`)开头的环境变量,因此可以安全地暴露给客户端代码。 值在构建时静态替换。 ```ts import { PUBLIC_BASE_URL } from '$env/static/public'; ```
# $lib
SvelteKit 自动将 `src/lib` 目录下的文件通过 `$lib` 导入别名使其可用。您可以在您的 [配置文件](configuration#files) 中更改此别名指向的目录。 ```svelte A reusable component ``` ```svelte ```
# $service-worker
```js // @noErrors import { base, build, files, prerendered, version } from '$service-worker'; ``` 此模块仅对[服务工作者](/docs/kit/service-workers)可用。 ## 基础 部署的`基本`路径。通常这等同于`config.kit.paths.base`,但它是由`location.pathname`计算得出的,这意味着如果网站部署到子目录中,它仍然可以正确工作。请注意,存在一个`基本`但没有`资源`,因为如果指定了`config.kit.paths.assets`,则无法使用服务工作者。 ```dts const base: string; ``` ## 构建 一个表示由 Vite 生成的文件的 URL 字符串数组,适用于与 `cache.addAll(build)` 一起缓存。在开发期间,这是一个空数组。 ```dts const build: string[]; ``` ## 文件 一个表示您静态目录中文件的 URL 字符串数组,或由`config.kit.files.assets`指定的任何目录。您可以使用 [`config.kit.serviceWorker.files`](/docs/kit/configuration) 自定义从`static`目录中包含哪些文件。 `const 文件: string[];` ## 预渲染 路径名数组,对应预渲染页面和端点。在开发期间,这是一个空数组。 ```dts const prerendered: string[]; ``` ## 版本 查看 [`config.kit.version`](/docs/kit/configuration#version)。这对于在您的服务工作者内部生成唯一的缓存名称很有用,以便您的应用程序的后续部署可以使旧缓存失效。 `const 版本:string;`
# Configuration
您的项目配置位于项目根目录下的 `svelte.config.js` 文件中。此外,SvelteKit 也使用此配置对象,以及其他与 Svelte 集成的工具,如编辑器扩展。 ```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; ``` ## 配置 扩展[`vite-plugin-svelte`的选项](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#svelte-options)。 ```dts interface Config extends SvelteConfig {/*…*/} ``` ```dts kit?: KitConfig; ``` SvelteKit 选项。 `[键:字符串]: 任何;` 任何需要与 Svelte 集成的工具所需的附加选项。 ## 套件配置 The `kit` 属性配置 SvelteKit,并可以具有以下属性: ## 适配器 * 默认`未定义` 您的[适配器](/docs/kit/adapters)在执行`vite build`时运行。它决定了输出如何转换为不同的平台。 ## 别名 * 默认`{}` 一个包含零个或多个别名的对象,用于替换 `import` 语句中的值。这些别名将自动传递给 Vite 和 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/*' } } }; ``` > \[!注意\] 内置的 `$lib` 别名由 `config.kit.files.lib` 控制,因为它用于打包。 > \[!注意\] 您需要运行 `npm run dev` 以使 SvelteKit 自动在 `jsconfig.json` 或 `tsconfig.json` 中生成所需的别名配置。 ## appDir * 默认`"_app"` 目录,其中 SvelteKit 存储其内容,包括静态资产(如 JS 和 CSS)以及内部使用的路由。 如果指定了 `paths.assets`,则会有两个应用程序目录 — `${paths.assets}/${appDir}` 和 `${paths.base}/${appDir}`。 ## csp [内容安全策略](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)配置。CSP 有助于保护您的用户免受跨站脚本(XSS)攻击,通过限制资源可以加载的位置。例如,这样的配置... ```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; ``` ...将阻止从外部站点加载脚本。SvelteKit 将为它生成的任何内联样式和脚本添加非 ces 或散列(取决于`模式`)以增强指定的指令。 要手动为包含在`src/app.html`中的脚本和链接添加 nonce,您可以使用占位符`%sveltekit.nonce%`(例如 ` ``` ## 路径 ```ts // @noErrors assets?: '' | `http://${string}` | `https://${string}`; ``` * 默认`""` 绝对路径,您的应用程序文件从中提供的服务路径。如果您的文件是从某种存储桶中提供服务的,这很有用。 ```ts // @noErrors base?: '' | `/${string}`; ``` * 默认`""` 根相对路径必须以`/`开头,但不能以`/`结尾(例如:`/base-path`),除非它是空字符串。这指定了您的应用程序从哪里提供服务,并允许应用程序存在于非根路径上。请注意,您需要将所有根相对链接都添加基本值作为前缀,否则它们将指向域的根,而不是您的`基本`(这就是浏览器的工作方式)。您可以使用从`$app/paths`中的`基本`[:](/docs/kit/$app-paths#base)进行此操作: `Link ` 。如果您经常编写此内容,将其提取为可重用组件可能是有意义的。 ```ts // @noErrors relative?: boolean; ``` * 默认`真` * 自 v1.9.0 起可用 是否使用相对资源路径。 如果 `true`,则从 `$app/paths` 导入的 `base` 和 `assets` 在服务器端渲染期间将被替换为相对资产路径,从而生成更易于携带的 HTML。如果 `false`,则 `%sveltekit.assets%` 和对构建实体的引用将始终是根相关路径,除非 `paths.assets` 是外部 URL。 [单页应用程序](/docs/kit/single-page-apps)回退页面将始终使用绝对路径,无论此设置如何。 如果您的应用使用了` `元素,您应该将其设置为`false`,否则资产 URL 将不正确地相对于` ` URL 解析,而不是当前页面。 在 1.0 版本中,`undefined`是一个有效的值,默认设置为该值。在这种情况下,如果`paths.assets`不是外部的,SvelteKit 会将`%sveltekit.assets%`替换为相对路径,并使用相对路径来引用构建工件,但从`$app/paths`导入的`base`和`assets`将按照您的配置指定。 ## 预渲染 查看[预渲染](/docs/kit/page-options#prerender)。 ```ts // @noErrors concurrency?: number; ``` * 默认`1` 一次可以预渲染多少页。JavaScript 是单线程的,但在预渲染性能受网络限制的情况下(例如从远程 CMS 加载内容),这可以通过在等待网络响应时处理其他任务来加快速度。 ```ts // @noErrors crawl?: boolean; ``` * 默认`真` 是否 SvelteKit 应通过跟随从`entries`的链接来查找需要预渲染的页面。 ```ts // @noErrors entries?: Array<'*' | `/${string}`>; ``` * 默认`["*"]` 一個待預渲染的頁面數組,或從此開始爬取(如果 `crawl: true`)。`*` 字符串包括所有不包含必需的 `[參數]` 且選項參數為空的路由(因為 SvelteKit 不清楚任何參數應該有何值)。 ```ts // @noErrors handleHttpError?: PrerenderHttpErrorHandlerValue; ``` * 默认`"失败"` * 自 v1.15.7 起可用 如何应对在预渲染应用时遇到的 HTTP 错误。 * `失败` — 构建失败 * `忽略` - 静默忽略失败并继续 * `警告` — 继续执行,但打印警告 * `(详细信息) => void` — 一个自定义错误处理器,它接受一个具有`状态`、`路径`、`来源`、`引用类型`和`消息`属性的`详细信息`对象。如果您从这个函数中`抛出异常`,构建将失败 ```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; ``` * 默认`"失败"` * 自 v1.15.7 起可用 如何应对从一个预渲染页面到另一个页面时,哈希链接与目标页面上的 `id` 不对应的情况。 * `失败` — 构建失败 * `忽略` - 静默忽略失败并继续 * `警告` — 继续执行,但打印警告 * `(详细信息) => void` — 一个自定义错误处理器,它接受一个具有`路径`、`id`、`引用者`和`消息`属性的`详细信息`对象。如果您从这个函数中`抛出`,构建将失败 ```ts // @noErrors handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue; ``` * 默认`"失败"` * 自 v1.16.0 起可用 如何应对由`entries`导出生成的条目与其生成的路由不匹配的情况。 * `失败` — 构建失败 * `忽略` - 静默忽略失败并继续 * `警告` — 继续执行,但打印警告 * `(详细信息) => void` — 一个自定义错误处理器,它接受一个具有 `generatedFromId`、`entry`、`matchedId` 和 `message` 属性的 `details` 对象。如果您从这个函数中 `throw`,构建将失败 ```ts // @noErrors origin?: string; ``` * 默认`"http://sveltekit-prerender"` The value of `url.origin` during prerendering; useful if it is included in rendered content. ## 路由器 ```ts // @noErrors type?: 'pathname' | 'hash'; ``` * 默认`"路径名"` * 自 v2.14.0 起可用 使用哪种客户端路由器。 * `‘pathname’`是默认值,表示当前 URL 的路径名决定路由 * `‘hash’` 表示路由由 `location.hash` 决定。在这种情况下,SSR 和预渲染被禁用。只有在 `pathname` 不可选时才推荐这样做,例如,因为你无法控制部署应用程序的 web 服务器。它带来了一些注意事项:你不能使用服务器端渲染(或者确实任何服务器逻辑),并且你必须确保你的应用程序中的所有链接都以 #/ 开头,否则它们将无法工作。除此之外,一切工作方式都与正常的 SvelteKit 应用程序完全相同。 ```ts // @noErrors resolution?: 'client' | 'server'; ``` * 默认`"客户端"` * 自 v2.17.0 起可用 如何确定在导航到新页面时加载哪条路由。 默认情况下,SvelteKit 将为浏览器提供路由清单。在导航时,此清单(以及如果存在,则使用`reroute`钩子)用于确定要加载哪些组件以及要运行哪些`load`函数。因为所有操作都在客户端进行,所以这个决定可以立即做出。缺点是必须在第一次导航之前加载和解析清单,如果您的应用程序包含许多路由,这可能会产生影响。 或者,SvelteKit 可以在服务器上确定路由。这意味着对于每个导航到尚未访问的路径,服务器将被要求确定路由。这有几个优点: * 客户端无需预先加载路由清单,这可以导致页面初始加载更快 * 路由列表对公众隐藏 * 服务器有机会拦截每次导航(例如通过中间件),从而实现(例如)对 SvelteKit 不可见的 A/B 测试 缺点是对于未访问的路径,解析将稍微花费更长的时间(尽管这可以通过[预加载](/docs/kit/link-options#data-sveltekit-preload-data)来缓解)。 > \[注意\] 当使用服务器端路由解析和预渲染时,解析将与路由本身一起预渲染。 ## 服务工作者 ```ts // @noErrors register?: boolean; ``` * 默认`真` 是否自动注册存在的服务工作者。 ```ts // @noErrors files?(filepath: string): boolean; ``` * 默认 `(filename) => !/\.DS_Store/.test(filename)` 确定你的 `static` 目录中哪些文件将在 `$service-worker.files` 中可用。 ## typescript ```ts // @noErrors config?: (config: Record) => Record | void; ``` * 默认`(配置) => 配置` * 自 v1.3.0 起可用 一个允许您编辑生成的`tsconfig.json`的函数。您可以修改配置(推荐)或返回一个新的配置。这在扩展 monorepo 根目录中的共享`tsconfig.json`时非常有用。 ## 版本 客户端导航可能会出现 bug,如果您在用户使用应用时部署新版本,如果新页面的代码已经加载,它可能包含过时内容;如果没有加载,应用的路线清单可能指向一个不再存在的 JavaScript 文件。SvelteKit 通过版本管理帮助您解决这个问题。如果 SvelteKit 在加载页面时遇到错误并检测到已部署新版本(使用此处指定的`name`,默认为构建的时间戳),它将回退到传统的全页导航。并非所有导航都会导致错误,例如,如果下一页的 JavaScript 已经加载。如果您仍然想在这些情况下强制全页导航,请使用设置`pollInterval`然后使用`beforeNavigate`等技术。 ```html /// file: +layout.svelte ``` 如果您将`pollInterval`设置为非零值,SvelteKit 将在后台轮询新版本,并在检测到新版本时将`[updated.current](/docs/kit/$app-state#updated)``true`的值设置为。 `` // @noErrors `没有错误 名称?: 字符串;` `` 当前应用版本字符串。如果指定,则必须是确定的(例如,提交引用而不是 `Math.random()` 或 `Date.now().toString()`),否则默认为构建的时间戳。 例如,要使用当前的提交哈希,您可以这样做:使用 `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; ``` * 默认`0` 毫秒级的轮询版本更改的间隔。如果这是 `0`,则不进行轮询。
# Command Line Interface
SvelteKit 项目使用[Vue](https://vitejs.dev),这意味着你将主要使用其 CLI(尽管是通过`npm run dev/build/preview`脚本): * `vite 开发` — 启动开发服务器 * `使用 vite 构建` — 构建您的应用程序的生产版本 * `vite 预览` — 在本地运行生产版本 然而,SvelteKit 包含用于初始化项目的自带 CLI: ## svelte-kit 同步 `使用 svelte-kit 同步`会创建`tsconfig.json`以及所有生成的类型(您可以在路由文件中将其导入为`./$types`),供您的项目使用。当您创建一个新项目时,它会被列为`准备`脚本,并作为 npm 生命周期的一部分自动运行,因此您通常不需要运行此命令。
# Types
## 生成类型 请求处理器`RequestHandler`和`Load`类型都接受一个`Params`参数,允许您输入`params`对象。例如,此端点期望`foo`、`bar`和`baz`参数: ```js /// file: src/routes/[foo]/[bar]/[baz]/+server.js // @errors: 2355 2322 1360 /** @type {import('@sveltejs/kit').RequestHandler<{ foo: string; bar: string; baz: string }>} */ export async function GET({ params }) { // ... } ``` 不用说,这写起来很麻烦,而且不太便携(如果你要将`[foo]`目录重命名为`[qux]`,类型将不再反映现实)。 为了解决这个问题,SvelteKit 为您的每个端点和页面生成`.d.ts`文件: ```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 RequestHandler = Kit.RequestHandler; export type PageLoad = Kit.Load; ``` 这些文件可以导入到您的端点和页面中作为同级,多亏了 TypeScript 配置中的[`rootDirs`](https://www.typescriptlang.org/tsconfig#rootDirs)选项: ```js /// file: src/routes/[foo]/[bar]/[baz]/+server.js // @filename: $types.d.ts import type * as Kit from '@sveltejs/kit'; type RouteParams = { foo: string; bar: string; baz: string; } export type RequestHandler = Kit.RequestHandler; // @filename: index.js // @errors: 2355 2322 // ---cut--- /** @type {import('./$types').RequestHandler} */ 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 }) { // ... } ``` 返回类型通过 `$types` 模块分别作为 `PageData` 和 `LayoutData` 可用,而所有 `Actions` 返回值的并集则可用作 `ActionData`。 从版本 2.16.0 开始,提供了两种额外的辅助类型:\``PageProps`\`定义了\``data: PageData`\`,以及当定义了操作时,\``form: ActionData`\`,而\``LayoutProps`\`定义了\``data: LayoutData`\`,以及\``children: Snippet`\`。 ```svelte ``` > \[!旧版\] 在 2.16.0 之前: > > ```svelte > > > ``` > > 使用 Svelte 4: > > ```svelte > > > ``` > \[!注意\] 要使此功能正常工作,您的自己的 `tsconfig.json` 或 `jsconfig.json` 应从生成的 `.svelte-kit/tsconfig.json` 扩展(其中 `.svelte-kit` 是您的 [`outDir`](configuration#outDir)): > > `{ "extends": "./.svelte-kit/tsconfig.json" }` ### 默认 tsconfig.json 生成的 `.svelte-kit/tsconfig.json` 文件包含多种选项。其中一些是根据您的项目配置自动生成的,通常在没有充分理由的情况下不应更改: ```json /// file: .svelte-kit/tsconfig.json { "compilerOptions": { "paths": { "$lib": ["../src/lib"], "$lib/*": ["../src/lib/*"] }, "rootDirs": ["..", "./types"] }, "include": [ "ambient.d.ts", "non-ambient.d.ts", "./types/**/$types.d.ts", "../vite.config.js", "../vite.config.ts", "../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte", "../tests/**/*.js", "../tests/**/*.ts", "../tests/**/*.svelte" ], "exclude": [ "../node_modules/**", "../src/service-worker.js", "../src/service-worker/**/*.js", "../src/service-worker.ts", "../src/service-worker/**/*.ts", "../src/service-worker.d.ts", "../src/service-worker/**/*.d.ts" ] } ``` 其他人需要 SvelteKit 正常运行,除非你了解自己在做什么,否则应保持不变: ```json /// file: .svelte-kit/tsconfig.json { "compilerOptions": { // this ensures that types are explicitly // imported with `import type`, which is // necessary as Svelte/Vite cannot // otherwise compile components correctly "verbatimModuleSyntax": true, // Vite compiles one TypeScript module // at a time, rather than compiling // the entire module graph "isolatedModules": true, // Tell TS it's used only for type-checking "noEmit": true, // This ensures both `vite build` // and `svelte-package` work correctly "lib": ["esnext", "DOM", "DOM.Iterable"], "moduleResolution": "bundler", "module": "esnext", "target": "esnext" } } ``` ## $lib 这是一个简单的别名,指向 `src/lib` 或指定的任何目录,例如 [`config.kit.files.lib`](configuration#files)。它允许您在不使用 `../../../../` 无聊的路径的情况下访问常用组件和实用模块。 ### $lib/server 子目录位于`$lib`中。SvelteKit 将阻止您将`$lib/server`中的任何模块导入到客户端代码中。请参阅[仅服务器端模块](server-only-modules)。 ## app.d.ts The `app.d.ts` 文件是您应用程序的环境类型所在之处,即无需显式导入即可使用的类型。 始终是此文件的一部分是 `App` 命名空间。此命名空间包含几个影响您交互的某些 SvelteKit 功能的类型的形状。 ## 错误 定义了预期和意外错误的通用形状。预期错误通过使用`error`函数抛出。意外错误由`handleError`钩子处理,这些钩子应返回此形状。 `接口 Error {/*…*/}` `消息:字符串;` ## 本地 接口定义了 `event.locals`,该变量可在服务器 [钩子](/docs/kit/hooks)(`handle` 和 `handleError`)、仅服务器 `load` 函数以及 `+server.js` 文件中访问。 `接口 Locals {}` ## 页面数据 定义了[页面数据状态](/docs/kit/$app-state#page)的通用形状以及\[ $page.data store](/docs/kit/$ app-stores#page) - 即,所有页面之间共享的数据。在`./$types`中的`Load`和`ServerLoad`函数将被相应地缩小。对于仅在特定页面上存在的数据,使用可选属性。不要添加索引签名(`[key: string]: any`)。 `接口 PageData {}` ## 页面状态 页面状态对象 `page.state` 的形状,可以使用来自 `$app/navigation` 的 [`pushState`](/docs/kit/$app-navigation#pushState) 和 [`replaceState`](/docs/kit/$app-navigation#replaceState) 函数进行操作。 `页面状态接口 {}` ## 平台 如果您的适配器通过 [平台特定上下文](/docs/kit/adapters#Platform-specific-context) 通过 `event.platform` 提供,您可以在此指定它。 `平台接口 {}`
# Start of the Svelte CLI documentation
# Overview
命令行界面(CLI),`sv`,是用于创建和维护 Svelte 应用程序的工具包。 ## 使用 最简单运行`sv`的方法是使用`npx`(或者如果你使用的是不同的包管理器,则使用等效命令——例如,如果你使用[pnpm](https://pnpm.io/),则使用`pnpx`): ```bash npx sv ``` 如果您在一个已安装 `sv` 的项目中,这将使用本地安装,否则它将下载最新版本并运行它而不进行安装,这对于 [`sv create`](sv-create) 特别有用。 ## 致谢 感谢[Christopher Brown](https://github.com/chbrown),他是 npm 上`sv`名称的原始所有者,慷慨地允许将其用于 Svelte CLI。您可以在[`@chbrown/sv`](https://www.npmjs.com/package/@chbrown/sv)找到原始的`sv`包。
# Frequently asked questions
## 如何运行 `sv` 命令行界面? 运行`sv`在各个包管理器中看起来略有不同。以下是最常见的命令列表: * **npm** : `npx sv create` * pnpm : `pnpx sv create` 或 `pnpm dlx sv create` * **面包** : `bunx sv create` * **Den** : `deno run npm:sv create` * **Yarn** : `yarn dlx sv create` ## `npx sv` 不工作 某些包管理器更喜欢运行本地安装的工具,而不是从注册表中下载和执行包。这个问题主要出现在`npm`和`yarn`上。这通常会导致错误消息,或者看起来你尝试执行的命令没有做任何事情。 以下是一份用户在过去遇到的问题及其可能解决方案的列表: * [ `npx sv` 创建没有任何作用](https://github.com/sveltejs/cli/issues/472) * [ `sv`命令名与`runit`冲突](https://github.com/sveltejs/cli/issues/259) * [ `sv` 在 Windows PowerShell 中与 `Set-Variable` 冲突](https://github.com/sveltejs/cli/issues/317)
# sv create
`sv create` 设置一个新的 SvelteKit 项目,并提供选项以 [设置附加功能](sv-add#Official-add-ons)。 ## 使用 ```bash npx sv create [options] [path] ``` ## 选项 ### `–模板` 使用哪个项目模板: * `minimal` — 为您的新应用提供基本框架 * `demo` — 展示应用,包含一个无需 JavaScript 即可运行的猜词游戏 * `库` — Svelte 库模板,使用 `svelte-package` 设置 ### `–类型 ` 是否以及如何为项目添加类型检查: * `ts` — 默认为 `.ts` 文件,并使用 `lang="ts"` 为 `.svelte` 组件 * `jsdoc` — 使用 [JSDoc 语法](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html) 进行类型定义 ### `–无类型` 防止添加类型检查。不推荐! ### `无插件` 运行命令时不要带交互式插件提示 ### `–安装` 使用指定的包管理器安装依赖项: * `npm` * `pnpm` * `yarn` * `面包` * `deno` ### `不安装` 阻止安装依赖项。
# sv add
`sv add` 更新现有项目以添加新功能。 ## 使用 `` npx sv add `使用 npx 添加` `` `npx sv add [插件]` 您可以从以下列表中选择多个以空格分隔的附加组件:[如下所示](#Official-add-ons),或者您可以使用交互式提示。 ## 选项 * `-C`,`--cwd` — 您的 Svelte(Kit) 项目的根路径 * `无前置条件` — 跳过检查前置条件 * `–安装` — 使用指定的包管理器安装依赖项 * `–no-install` — 阻止安装依赖 ## 官方插件 * [`drizzle`](drizzle) * [`eslint`](eslint) * [ `露西亚`](lucia) * [`mdsvex`](mdsvex) * [ `滑翔伞`](paraglide) * [`playwright`](playwright) * [`prettier`](prettier) * [`storybook`](storybook) * [ `斯威夫特套件适配器`](sveltekit-adapter) * [`tailwindcss`](tailwind) * [`vitest`](vitest) * [`devtools-json`](devtools-json)
# sv check
`sv 检查` 查找您项目中的错误和警告,例如: * 未使用 CSS * 无障碍提示 * JavaScript/TypeScript 编译器错误 需要 Node 16 或更高版本。 ## 安装 您需要在项目中安装 `svelte-check` 包: ```bash npm i -D svelte-check ``` ## 使用 `npx sv 检查` ## 选项 ### `--工作空间 ` 工作空间路径。除了`node_modules`和`--ignore`中列出的子目录外,所有子目录都将进行检查。 ### `输出` 如何显示错误和警告。参见[机器可读输出](#Machine-readable-output)。 * `人类` * `人-详细` * `机器` * `机器详细` ### `–观察` 保持进程运行并监视更改。 ### `保留监视输出` 防止在监视模式下清除屏幕。 ### `–tsconfig` 传递一个 `tsconfig` 或 `jsconfig` 文件的路径。路径可以是相对于工作区路径的相对路径或绝对路径。这样做意味着只有与配置文件中的 `files`/`include`/`exclude` 模式匹配的文件才会被诊断。这也意味着会报告 TypeScript 和 JavaScript 文件的错误。如果没有提供,将向上遍历项目目录以查找下一个 `jsconfig`/`tsconfig.json` 文件。 ### `–无 tsconfig` 使用此选项仅检查当前目录及其下找到的 Svelte 文件,并忽略任何 `.js`/`.ts` 文件(它们将不会进行类型检查) ### `忽略 ` 文件/文件夹忽略列表,相对于工作区根目录。路径应以逗号分隔并用引号括起来。示例: ```bash npx sv check --ignore "dist,build" ``` 仅当与`--no-tsconfig`结合使用时才有效。当与`--tsconfig`结合使用时,这只会影响监视的文件,而不是诊断的文件,后者由`tsconfig.json`决定。 ### `在警告时失败` 如果提供,警告将导致`sv 检查`以错误代码退出。 ### `--compiler-warnings ` 一个以逗号分隔的引用列表,包含`代码:行为`对,其中`代码`是[编译器警告代码](../svelte/compiler-warnings),而`行为`是`忽略`或`错误`: ```bash npx sv check --compiler-warnings "css_unused_selector:ignore,a11y_missing_attribute:error" ``` ### `--diagnostic-sources ` 一个逗号分隔的源列表,这些源应该对您的代码运行诊断。默认情况下,所有源都处于活动状态: * `js`(包括 TypeScript) * `斯维特` * `css` 示例: ```bash npx sv check --diagnostic-sources "js,svelte" ``` ### `阈值<` 过滤诊断: * `警告`(默认)— 显示错误和警告 * `错误` — 只显示错误 ## 故障排除 [查看语言工具文档](https://github.com/sveltejs/language-tools/blob/master/docs/README.md)以获取有关预处理器设置和其他故障排除的更多信息。 ## 可读机输出 设置 `–输出` 为 `机器` 或 `机器-详细` 将以更易于机器阅读的方式格式化输出,例如在 CI 管道中、进行代码质量检查等。 每行对应一条新记录。行由单个空格字符分隔的列组成。每行的第一列包含一个时间戳(以毫秒为单位),可用于监控目的。第二列提供了“行类型”,根据此类型,后续列的数量和类型可能会有所不同。 第一行是类型为 `START`,并包含工作空间文件夹(用引号括起来)。示例: ``` 1590680325583 START "/home/user/language-tools/packages/language-server/test/plugins/typescript/testfiles" ``` 任何数量的`错误`或`警告`记录可能随后出现。它们的结构相同,取决于输出参数。 如果参数是 `machine`,它将告诉我们文件名、起始行和列号以及错误信息。文件名相对于工作区目录。文件名和消息都包含在引号内。示例: ``` 1590680326283 ERROR "codeactions.svelte" 1:16 "Cannot find module 'blubb' or its corresponding type declarations." 1590680326778 WARNING "imported-file.svelte" 0:37 "Component has unused export property 'prop'. If it is for external reference only, please consider using `export const prop`" ``` 如果参数是 `machine-verbose`,它将告诉我们文件名、起始行和列号、结束行和列号、错误信息、诊断代码、代码的人类友好描述以及诊断的人类友好来源(例如:svelte/typescript)。文件名相对于工作区目录。每个诊断都表示为以日志时间戳为前缀的 [ndjson](https://en.wikipedia.org/wiki/JSON_streaming#Newline-Delimited_JSON) 行。示例: ``` 1590680326283 {"type":"ERROR","fn":"codeaction.svelte","start":{"line":1,"character":16},"end":{"line":1,"character":23},"message":"Cannot find module 'blubb' or its corresponding type declarations.","code":2307,"source":"js"} 1590680326778 {"type":"WARNING","filename":"imported-file.svelte","start":{"line":0,"character":37},"end":{"line":0,"character":51},"message":"Component has unused export property 'prop'. If it is for external reference only, please consider using `export const prop`","code":"unused-export-let","source":"svelte"} ``` 输出以一个`完成`消息结束,该消息总结了在检查过程中遇到的文件总数、错误和警告。示例: ``` 1590680326807 COMPLETED 20 FILES 21 ERRORS 1 WARNINGS 3 FILES_WITH_PROBLEMS ``` 如果应用程序在运行时遇到错误,此错误将显示为 `失败` 记录。示例: ``` 1590680328921 FAILURE "Connection closed" ``` ## 致谢 * Vue 的[VTI](https://github.com/vuejs/vetur/tree/master/vti)为`svelte-check`奠定了基础 ## 常见问题解答 ### 为什么没有只检查特定文件(例如只检查暂存文件)的选项? `سوفتلی-چک` 需要查看整个项目以确保检查有效。假设你重命名了一个组件属性,但没有更新任何使用该属性的地方——现在所有使用位置都是错误,但如果只对更改的文件进行检查,你可能会错过它们。
# sv migrate
`sv 迁移` 迁移 Svelte(Kit) 代码库。它委托给 [`sv-migrate`](https://www.npmjs.com/package/svelte-migrate) 包。 某些迁移可能会在您的代码库中添加待完成的任务注释,您可以通过搜索`@迁移`来找到这些任务。 ## 使用 `npx sv 迁移` 您也可以通过命令行直接指定迁移: `npx sv 迁移 [迁移]` ## 迁移 ### `应用状态` 迁移 `$app/stores` 使用到 `$app/state` 在 `.svelte` 文件中。查看 [迁移指南](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated) 了解更多详情。 ### `斯维特-5` 升级 Svelte 4 应用以使用 Svelte 5,并更新单个组件以使用 [runes](../svelte/what-are-runes) 和其他 Svelte 5 语法([查看迁移指南](../svelte/v5-migration-guide))。 ### `自闭合标签` 替换您所有 `.svelte` 文件中的自闭合非空元素。有关更多详细信息,请参阅 [拉取请求](https://github.com/sveltejs/kit/pull/12128)。 ### `斯维特 4` 升级 Svelte 3 应用程序以使用 Svelte 4([查看迁移指南](../svelte/v4-migration-guide))。 ### `斯威夫特套件-2` 升级 SvelteKit 1 应用到 SvelteKit 2([查看迁移指南](../kit/migrating-to-sveltekit-2))。 ### `包` 升级使用 `@sveltejs/package` 版本 1 的库到版本 2。请参阅 [拉取请求](https://github.com/sveltejs/kit/pull/8922) 获取更多详细信息。 ### `路由` 升级预发布版 SvelteKit 应用程序以使用 SvelteKit 1 的文件系统路由约定。请参阅[拉取请求](https://github.com/sveltejs/kit/discussions/5774)获取更多详细信息。
# devtools-json
The `devtools-json` 插件安装了 [`vite-plugin-devtools-json`](https://github.com/ChromeDevTools/vite-plugin-devtools-json/),这是一个用于在开发服务器上实时生成 Chromium DevTools 项目设置文件的 Vite 插件。此文件从 `/.well-known/appspecific/com.chrome.devtools.json` 提供服务,并告知 Chromium 浏览器您的项目源代码的位置,以便您可以使用 [工作区功能](https://developer.chrome.com/docs/devtools/workspaces) 在浏览器中编辑源文件。 > \[!注意\] 安装此插件将启用所有使用 Chromium 浏览器连接到开发服务器的用户的功能,并允许浏览器读取和写入目录中的所有文件。如果使用 Chrome 的 AI 辅助功能,这也可能导致数据被发送到 Google。 ## 替代方案 如果您不想安装插件,但又想避免看到关于缺失文件的提示,您有几个选择。 首先,您可以通过在浏览器中禁用功能来防止您的机器发出请求。您可以在 Chrome 中通过访问`chrome://flags`并禁用“开发者工具项目设置”来实现这一点。您可能还对禁用“开发者工具自动工作区文件夹”感兴趣,因为它与之密切相关。 您也可以通过自行处理请求来防止 Web 服务器向您的应用程序的所有开发者发出有关传入请求的通知。例如,您可以创建一个名为 `.well-known/appspecific/com.chrome.devtools.json` 的文件,内容为`"Go away, Chrome DevTools!"`,或者您可以在您的[`handle`](https://svelte.dev/docs/kit/hooks#Server-hooks-handle)钩子中添加逻辑来响应请求: ```js /// file: src/hooks.server.js import { dev } from '$app/environment'; export function handle({ event, resolve }) { if (dev && event.url.pathname === '/.well-known/appspecific/com.chrome.devtools.json') { return new Response(undefined, { status: 404 }); } return resolve(event); } ``` ## 使用 ```bash npx sv add devtools-json ``` ## 您将获得 * `vite-plugin-devtools-json` 添加到您的 Vite 插件选项中
# drizzle
[Drizzle ORM](https://orm.drizzle.team/) 是一款提供关系型和类似 SQL 查询 API 的 TypeScript ORM,并且设计上已准备好无服务器化。 ## 使用 ```bash npx sv add drizzle ``` ## 您将获得 * 一套将您的数据库访问保留在 SvelteKit 服务器文件中的设置 * 一个 `.env` 文件来存储您的凭证 * 兼容 Lucia 认证插件 * 一个可选的 Docker 配置,以帮助运行本地数据库 ## 选项 ### 数据库 使用哪个数据库变体: * `postgresql` — 最受欢迎的开源数据库 * `mysql` — 另一种流行的开源数据库 * `sqlite` — 基于文件的数据库,无需数据库服务器 ```bash npx sv add drizzle=database:postgresql ``` ### 客户端 使用 SQL 客户端取决于`数据库`: * 对于`postgresql`:`postgres.js`,`neon`, * 对于`mysql`:`mysql2`,`planetscale` * 对于`sqlite`:`better-sqlite3`,`libsql`,`turso` ```bash npx sv add drizzle=database:postgresql+client:postgres.js ``` Drizzle 与超过一打数据库驱动程序兼容。我们只是为了简化,在这里提供了一些最常见的选择,但如果你想使用另一个,你可以在设置后选择一个占位符,并从[Drizzle 的完整兼容驱动程序列表](https://orm.drizzle.team/docs/connect-overview#next-steps)中选择来替换它。 ### docker 是否添加 Docker Compose 配置。仅适用于[`数据库`](#Options-database)`postgresql`或`mysql` ```bash npx sv add drizzle=database:postgresql+client:postgres.js+docker:yes ```
# eslint
[ESLint](https://eslint.org/) 查找并修复您的代码中的问题。 ## 使用 `` npx sv add eslint `使用 npx sv add eslint 添加 eslint` `` ## 您将获得 * 相关已安装的包包括 `eslint-plugin-svelte` * 一个 `eslint.config.js` 文件 * 更新 `.vscode/settings.json` * 配置为与 TypeScript 和 `prettier` 兼容,如果您使用这些包
# lucia
一个遵循[Lucia 身份验证指南](https://lucia-auth.com/)的身份验证设置。 ## 使用 ```bash npx sv add lucia ``` ## 您将获得 * 一个遵循 Lucia 认证指南最佳实践的 SvelteKit 和 Drizzle 认证设置 * 可选的演示注册和登录页面 ## 选项 ### 演示 是否包含演示注册和登录页面。 ```bash npx sv add lucia=demo:yes ```
# mdsvex
[mdsvex](https://mdsvex.pngwn.io) 是 Svelte 组件的 markdown 预处理器 - 基本上等同于 Svelte 的 MDX。它允许你在 markdown 中使用 Svelte 组件,或者在 Svelte 组件中使用 markdown。 ## 使用 ```bash npx sv add mdsvex ``` ## 您将获得 * mdsvex 已在您的 `svelte.config.js` 中安装和配置
# paraglide
[浪浪翼伞](https://inlang.com/m/gerre34r/library-inlang-paraglideJs) 是一个基于编译器的 i18n 库,它生成可摇树(tree-shakable)的消息函数,具有小型包大小、无异步瀑布、完全类型安全等功能。 ## 使用 ```bash npx sv add paraglide ``` ## 您将获得 * Inlang 项目设置 * 滑翔伞 Vite 插件 * SvelteKit `reroute` 和 `handle` 钩子 * `text-direction` 和 `lang` 属性在 `app.html` 中 * 更新 `.gitignore` * 一个可选的演示页面,展示如何使用滑翔伞 ## 选项 ### 语言标签 您希望支持的编程语言指定为 IETF BCP 47 语言标签。 ```bash npx sv add paraglide="languageTags:en,es" ``` ### 演示 是否生成一个可选的演示页面,展示如何使用滑翔伞。 ```bash npx sv add paraglide="demo:yes" ```
# playwright
[剧本作家](https://playwright.dev) 浏览器测试。 ## 使用 ```bash npx sv add playwright ``` ## 您将获得 * 脚本添加到您的 `package.json` 中 * 一个 Playwright 配置文件 * 一个更新的`.gitignore` * 一个演示测试
# prettier
[代码格式化工具](https://prettier.io)是一个有偏见的代码格式化器。 ## 使用 `` npx sv add prettier `使用 npx sv add prettier 命令` `` ## 您将获得 * 脚本在您的`package.json`中 * `.prettierignore` 和 `.prettierrc` 文件 * 更新您的 eslint 配置,如果您正在使用该软件包
# storybook
[故事书](https://storybook.js.org/)是一个前端组件工作坊。 ## 使用 `npx sv 添加 storybook` ## 您将获得 * `npx storybook init` 在相同的方便的 `sv` CLI 中为您运行,该 CLI 也用于所有其他插件 * [Storybook for SvelteKit](https://storybook.js.org/docs/get-started/frameworks/sveltekit) 或 [Storybook for Svelte & Vite](https://storybook.js.org/docs/get-started/frameworks/svelte-vite) 提供默认配置,轻松模拟许多 SvelteKit 模块,自动处理链接,更多功能。
# sveltekit-adapter
[SvelteKit 适配器](/docs/kit/adapters) 允许您将您的网站部署到多个平台。此附加组件允许您配置官方提供的 SvelteKit 适配器,但还有许多[社区提供的适配器](https://www.sveltesociety.dev/packages?category=sveltekit-adapters)也可用。 ## 使用 ```bash npx sv add sveltekit-adapter ``` ## 您将获得 * 所选的 SvelteKit 适配器已安装并配置在您的`svelte.config.js`中 ## 选项 ### 适配器 使用哪个 SvelteKit 适配器: * `auto` — [`@sveltejs/adapter-auto`](/docs/kit/adapter-auto) 自动选择合适的适配器,但配置性较低 * `node` — [`@sveltejs/adapter-node`](/docs/kit/adapter-node) 生成一个独立的 Node 服务器 * `静态` — [`@sveltejs/adapter-static`](/docs/kit/adapter-static) 允许您使用 SvelteKit 作为静态网站生成器 (SSG) * `vercel` — [`@sveltejs/adapter-vercel`](/docs/kit/adapter-vercel) 允许您部署到 Vercel * `cloudflare` — [`@sveltejs/adapter-cloudflare`](/docs/kit/adapter-cloudflare) 允许您部署到 Cloudflare * `netlify` — [`@sveltejs/adapter-netlify`](/docs/kit/adapter-netlify) 允许您部署到 Netlify ```bash npx sv add sveltekit-adapter=adapter:node ```
# tailwindcss
[Tailwind CSS](https://tailwindcss.com/) 允许您在不离开 HTML 的情况下快速构建现代网站。 ## 使用 ```bash npx sv add tailwindcss ``` ## 您将获得 * Tailwind 集成遵循 [Tailwind for SvelteKit 指南](https://tailwindcss.com/docs/installation/framework-guides/sveltekit) * Tailwind Vite 插件 * 更新 `app.css` 和 `+layout.svelte`(用于 SvelteKit)或 `App.svelte`(用于非 SvelteKit Vite 应用程序) * 集成使用`prettier`的包 ## 选项 ### 插件 哪个插件可以使用: * `排版` — [`@tailwindcss/排版`](https://github.com/tailwindlabs/tailwindcss-typography) * `表单` — [`@tailwindcss/forms`](https://github.com/tailwindlabs/tailwindcss-forms) ```bash npx sv add tailwindcss="plugins:typography" ```
# vitest
[vitest](https://vitest.dev/) 是一个 Vite 原生测试框架。 ## 使用 `npx sv 添加 vitest` ## 您将获得 * 相关包已安装,并将脚本添加到您的 `package.json` 中 * 客户端/服务器感知的 Svelte 测试设置,在你的 Vite 配置文件中 * 演示测试