Skip to main content

配置

你的项目配置位于项目根目录的 svelte.config.js 文件中。与 SvelteKit 一样,此配置对象还被其他与 Svelte 集成的工具(例如编辑器扩展)使用。

¥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.

svelte.config
import const adapter: () => import("@sveltejs/kit").Adapteradapter from '@sveltejs/adapter-auto';

/** @type {import('@sveltejs/kit').Config} */
const const config: Config
@type{import('@sveltejs/kit').Config}
config
= {
Config.kit?: KitConfig | undefined

SvelteKit options

kit
: {
KitConfig.adapter?: Adapter | undefined

Your adapter is run when executing vite build. It determines how the output is converted for different platforms.

@defaultundefined
adapter
: function adapter(): import("@sveltejs/kit").Adapteradapter()
} }; export default const config: Config
@type{import('@sveltejs/kit').Config}
config
;

配置(Config)

¥Config

interface Config {}
compilerOptions?: CompileOptions;
  • 默认 {}

    ¥default {}

传递给 svelte.compile 的选项。

¥Options passed to svelte.compile.

extensions?: string[];
  • 默认 [".svelte"]

    ¥default [".svelte"]

应视为 Svelte 文件的文件扩展名列表。

¥List of file extensions that should be treated as Svelte files.

kit?: KitConfig;

SvelteKit 选项

¥SvelteKit options

preprocess?: any;

预处理器选项(如果有)。也可以通过 Vite 的预处理器功能进行预处理。

¥Preprocessor options, if any. Preprocessing can alternatively also be done through Vite’s preprocessor capabilities.

vitePlugin?: PluginOptions;

vite-plugin-svelte 插件选项。

¥vite-plugin-svelte plugin options.

[key: string]: any;

组件中的任何 规则都将进行类似调整:

¥Any additional options required by tooling that integrates with Svelte.

KitConfig

kit 属性配置 SvelteKit,并且可以具有以下属性:

¥The kit property configures SvelteKit, and can have the following properties:

adapter

  • 默认 undefined

    ¥default undefined

你的 adapter 在执行 vite build 时运行。它决定如何为不同的平台转换输出。

¥Your adapter is run when executing vite build. It determines how the output is converted for different platforms.

alias

  • 默认 {}

    ¥default {}

包含零个或多个别名的对象,用于替换 import 语句中的值。这些别名会自动传递给 Vite 和 TypeScript。

¥An object containing zero or more aliases used to replace values in import statements. These aliases are automatically passed to Vite and TypeScript.

svelte.config
/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        alias: {
 'my-file': string;
 'my-directory': string;
            'my-directory/*': string;
        };
    };
}
@type{import('@sveltejs/kit').Config}
config
= {
kit: {
    alias: {
        'my-file': string;
        'my-directory': string;
        'my-directory/*': string;
    };
}
kit
: {
alias: {
    'my-file': string;
    'my-directory': string;
    'my-directory/*': string;
}
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 控制,因为它用于打包。

¥[!NOTE] The built-in $lib alias is controlled by config.kit.files.lib as it is used for packaging.

你需要运行 npm run dev 才能让 SvelteKit 在 jsconfig.jsontsconfig.json 中自动生成所需的别名配置。

¥[!NOTE] You will need to run npm run dev to have SvelteKit automatically generate the required alias configuration in jsconfig.json or tsconfig.json.

appDir

  • 默认 "_app"

    ¥default "_app"

SvelteKit 保存其内容的目录,包括静态资源(例如 JS 和 CSS)和内部使用的路由。

¥The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes.

如果指定了 paths.assets,将有两个应用目录-${paths.assets}/${appDir}${paths.base}/${appDir}

¥If paths.assets is specified, there will be two app directories — ${paths.assets}/${appDir} and ${paths.base}/${appDir}.

csp

内容安全策略 配置。CSP 通过限制可以从中加载资源的位置,帮助保护你的用户免受跨站点脚本 (XSS) 攻击。例如,像这样的配置...

¥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...

svelte.config
/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        csp: {
 directives: {
   'script-src': string[];
 };
 reportOnly: {
   'script-src': string[];
   'report-uri': string[];
 };
        };
    };
}
@type{import('@sveltejs/kit').Config}
config
= {
kit: {
    csp: {
        directives: {
 'script-src': string[];
        };
        reportOnly: {
 'script-src': string[];
 'report-uri': string[];
        };
    };
}
kit
: {
csp: {
    directives: {
        'script-src': string[];
    };
    reportOnly: {
        'script-src': string[];
        'report-uri': string[];
    };
}
csp
: {
directives: {
    'script-src': string[];
}
directives
: {
'script-src': ['self'] }, // must be specified with either the `report-uri` or `report-to` directives, or both
reportOnly: {
    'script-src': string[];
    'report-uri': string[];
}
reportOnly
: {
'script-src': ['self'], 'report-uri': ['/'] } } } }; export default
const config: {
    kit: {
        csp: {
 directives: {
   'script-src': string[];
 };
 reportOnly: {
   'script-src': string[];
   'report-uri': string[];
            };
        };
    };
}
@type{import('@sveltejs/kit').Config}
config
;

...将阻止从外部站点加载脚本。SvelteKit 将使用 nonces 或哈希(取决于 mode)增强其生成的任何内联样式和脚本的指定指令。

¥...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.

要为手动包含在 src/app.html 中的脚本和链接添加随机数,你可以使用占位符 %sveltekit.nonce%(例如 <script nonce="%sveltekit.nonce%">)。

¥To add a nonce for scripts and links manually included in src/app.html, you may use the placeholder %sveltekit.nonce% (for example <script nonce="%sveltekit.nonce%">).

当页面预渲染时,CSP 标头通过 <meta http-equiv> 标记添加(请注意,在这种情况下,frame-ancestorsreport-urisandbox 指令将被忽略)。

¥When pages are prerendered, the CSP header is added via a <meta http-equiv> tag (note that in this case, frame-ancestors, report-uri and sandbox directives will be ignored).

mode'auto' 时,SvelteKit 将使用 nonce 来动态渲染页面,并使用哈希来预渲染页面。在预渲染页面中使用 nonce 是不安全的,因此是被禁止的。

¥[!NOTE] When mode is 'auto', SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden.

请注意,大多数 Svelte 转换 通过创建内联 <style> 元素来工作。如果你在应用中使用这些,则必须保留 style-src 指令未指定或添加 unsafe-inline

¥[!NOTE] Note that most Svelte transitions work by creating an inline <style> element. If you use these in your app, you must either leave the style-src directive unspecified or add unsafe-inline.

如果此级别的配置不足并且你有更多动态要求,则可以使用 handle 钩子 来推出自己的 CSP。

¥If this level of configuration is insufficient and you have more dynamic requirements, you can use the handle hook to roll your own CSP.

mode?: 'hash' | 'nonce' | 'auto';

是否使用哈希或随机数来限制 <script><style> 元素。'auto' 将对预渲染页面使用哈希,对动态渲染页面使用随机数。

¥Whether to use hashes or nonces to restrict <script> and <style> elements. 'auto' will use hashes for prerendered pages, and nonces for dynamically rendered pages.

directives?: CspDirectives;

将添加到 Content-Security-Policy 标头的指令。

¥Directives that will be added to Content-Security-Policy headers.

reportOnly?: CspDirectives;

将添加到 Content-Security-Policy-Report-Only 标头的指令。

¥Directives that will be added to Content-Security-Policy-Report-Only headers.

csrf

防范 跨站点请求伪造 (CSRF) 攻击。

¥Protection against cross-site request forgery (CSRF) attacks.

checkOrigin?: boolean;
  • 默认 true

    ¥default true

是否检查传入的 origin 标头中是否存在 POSTPUTPATCHDELETE 表单提交,并验证其是否与服务器的来源匹配。

¥Whether to check the incoming origin header for POST, PUT, PATCH, or DELETE form submissions and verify that it matches the server’s origin.

要允许人们从其他来源向你的应用发出 POSTPUTPATCHDELETE 请求,其中 Content-Typeapplication/x-www-form-urlencodedmultipart/form-datatext/plain,你需要禁用此选项。小心!

¥To allow people to make POST, PUT, PATCH, or DELETE requests with a Content-Type of application/x-www-form-urlencoded, multipart/form-data, or text/plain to your app from other origins, you will need to disable this option. Be careful!

embedded

  • 默认 false

    ¥default false

应用是否嵌入在更大的应用中。如果是 true,SvelteKit 会在 %sveltekit.body% 而不是 window 的父级上添加与导航等相关的事件监听器,并将从服务器传递 params,而不是从 location.pathname 推断它们。请注意,通常不支持在同一页面上嵌入多个 SvelteKit 应用并在其中使用客户端 SvelteKit 功能(诸如推送到历史状态之类的操作假设单个实例)。

¥Whether or not the app is embedded inside a larger app. If true, SvelteKit will add its event listeners related to navigation etc on the parent of %sveltekit.body% instead of window, and will pass params from the server rather than inferring them from location.pathname. Note that it is generally not supported to embed multiple SvelteKit apps on the same page and use client-side SvelteKit features within them (things such as pushing to the history state assume a single instance).

env

环境变量配置

¥Environment variable configuration

dir?: string;
  • 默认 "."

    ¥default "."

搜索 .env 文件的目录。

¥The directory to search for .env files.

publicPrefix?: string;
  • 默认 "PUBLIC_"

    ¥default "PUBLIC_"

表示环境变量可以安全地暴露给客户端代码的前缀。参见 $env/static/public$env/dynamic/public。请注意,如果你使用 Vite 的环境变量处理,则必须单独设置 Vite 的 envPrefix - 尽管通常不需要使用该功能。

¥A prefix that signals that an environment variable is safe to expose to client-side code. See $env/static/public and $env/dynamic/public. Note that Vite’s envPrefix must be set separately if you are using Vite’s environment variable handling - though use of that feature should generally be unnecessary.

privatePrefix?: string;
  • 默认 ""

    ¥default ""

  • v1.21.0 起可用

    ¥available since v1.21.0

表示环境变量不安全地暴露给客户端代码的前缀。既不匹配公共前缀也不匹配私有前缀的环境变量将被完全丢弃。参见 $env/static/private$env/dynamic/private

¥A prefix that signals that an environment variable is unsafe to expose to client-side code. Environment variables matching neither the public nor the private prefix will be discarded completely. See $env/static/private and $env/dynamic/private.

files

在你的项目中哪里可以找到各种文件。

¥Where to find various files within your project.

assets?: string;
  • 默认 "static"

    ¥default "static"

放置静态文件的位置,这些文件应具有稳定的 URL 并且不进行任何处理,例如 favicon.icomanifest.json

¥a place to put static files that should have stable URLs and undergo no processing, such as favicon.ico or manifest.json

hooks?: {}
client?: string;
  • 默认 "src/hooks.client"

    ¥default "src/hooks.client"

客户端 hooks 的位置。

¥The location of your client hooks.

server?: string;
  • 默认 "src/hooks.server"

    ¥default "src/hooks.server"

服务器 hooks 的位置。

¥The location of your server hooks.

universal?: string;
  • 默认 "src/hooks"

    ¥default "src/hooks"

  • 起可用 v2.3.0

    ¥available since v2.3.0

通用 hooks 的位置。

¥The location of your universal hooks.

lib?: string;
  • 默认 "src/lib"

    ¥default "src/lib"

你的应用的内部库,可在整个代码库中作为 $lib 访问

¥your app’s internal library, accessible throughout the codebase as $lib

params?: string;
  • 默认 "src/params"

    ¥default "src/params"

包含 参数匹配器 的目录

¥a directory containing parameter matchers

routes?: string;
  • 默认 "src/routes"

    ¥default "src/routes"

定义应用结构的文件(请参阅 路由

¥the files that define the structure of your app (see Routing)

serviceWorker?: string;
  • 默认 "src/service-worker"

    ¥default "src/service-worker"

服务工作者入口点的位置(请参阅 服务工作者

¥the location of your service worker’s entry point (see Service workers)

appTemplate?: string;
  • 默认 "src/app.html"

    ¥default "src/app.html"

HTML 响应模板的位置

¥the location of the template for HTML responses

errorTemplate?: string;
  • 默认 "src/error.html"

    ¥default "src/error.html"

后备错误响应模板的位置

¥the location of the template for fallback error responses

inlineStyleThreshold

  • 默认 0

    ¥default 0

在 HTML 头部的 <style> 块内内联 CSS。此选项是一个数字,用于指定要内联的 CSS 文件的最大长度(以 UTF-16 代码单元为单位),由 String.length 属性指定。页面所需的所有 CSS 文件以及小于此值的文件都合并并内联在 <style> 块中。

¥Inline CSS inside a <style> block at the head of the HTML. This option is a number that specifies the maximum length of a CSS file in UTF-16 code units, as specified by the String.length property, to be inlined. All CSS files needed for the page and smaller than this value are merged and inlined in a <style> block.

这可以减少初始请求并提高你的 First Contentful Paint 分数。但是,它会生成更大的 HTML 输出并降低浏览器缓存的有效性。请谨慎使用。

¥[!NOTE] This results in fewer initial requests and can improve your First Contentful Paint score. However, it generates larger HTML output and reduces the effectiveness of browser caches. Use it advisedly.

moduleExtensions

  • 默认 [".js", ".ts"]

    ¥default [".js", ".ts"]

SvelteKit 将视为模块的文件扩展名数组。路由将忽略扩展名与 config.extensionsconfig.kit.moduleExtensions 均不匹配的文件。

¥An array of file extensions that SvelteKit will treat as modules. Files with extensions that match neither config.extensions nor config.kit.moduleExtensions will be ignored by the router.

outDir

  • 默认 ".svelte-kit"

    ¥default ".svelte-kit"

SvelteKit 在 devbuild 期间将文件写入的目录。你应该将此目录排除在版本控制之外。

¥The directory that SvelteKit writes files to during dev and build. You should exclude this directory from version control.

output

与构建输出格式相关的选项

¥Options related to the build output format

preloadStrategy?: 'modulepreload' | 'preload-js' | 'preload-mjs';
  • 默认 "modulepreload"

    ¥default "modulepreload"

  • v1.8.4 起可用

    ¥available since v1.8.4

SvelteKit 将预加载初始页面所需的 JavaScript 模块以避免导入 ‘waterfalls’,从而加快应用启动速度。有三种策略,各有优缺点:

¥SvelteKit will preload the JavaScript modules needed for the initial page to avoid import ‘waterfalls’, resulting in faster application startup. There are three strategies with different trade-offs:

  • modulepreload - 使用 <link rel="modulepreload">。这在基于 Chromium 的浏览器、Firefox 115+ 和 Safari 17+ 中提供最佳效果。它在旧版浏览器中被忽略。

    ¥modulepreload - uses <link rel="modulepreload">. This delivers the best results in Chromium-based browsers, in Firefox 115+, and Safari 17+. It is ignored in older browsers.

  • preload-js - 使用 <link rel="preload">。防止 Chromium 和 Safari 中的瀑布,但 Chromium 会对每个模块进行两次解析(一次作为脚本,一次作为模块)。导致在 Firefox 中两次请求模块。如果你想以 Chromium 用户的轻微性能下降为代价最大限度地提高 iOS 设备用户的性能,这是一个很好的设置。

    ¥preload-js - uses <link rel="preload">. Prevents waterfalls in Chromium and Safari, but Chromium will parse each module twice (once as a script, once as a module). Causes modules to be requested twice in Firefox. This is a good setting if you want to maximise performance for users on iOS devices at the cost of a very slight degradation for Chromium users.

  • preload-mjs - 使用 <link rel="preload">,但使用 .mjs 扩展,可防止 Chromium 中的双重解析。一些静态 Web 服务器无法提供带有 Content-Type: application/javascript 标头的 .mjs 文件,这将导致你的应用崩溃。如果这不适用于你,那么这是为最多用户提供最佳性能的选项,直到 modulepreload 得到更广泛的支持。

    ¥preload-mjs - uses <link rel="preload"> but with the .mjs extension which prevents double-parsing in Chromium. Some static webservers will fail to serve .mjs files with a Content-Type: application/javascript header, which will cause your application to break. If that doesn’t apply to you, this is the option that will deliver the best performance for the largest number of users, until modulepreload is more widely supported.

bundleStrategy?: 'split' | 'single' | 'inline';
  • 默认 'split'

    ¥default 'split'

  • v2.13.0 起可用

    ¥available since v2.13.0

打包策略选项会影响应用的 JavaScript 和 CSS 文件的加载方式。

¥The bundle strategy option affects how your app’s JavaScript and CSS files are loaded.

  • 如果是 'split',则将应用拆分为多个 .js/.css 文件,以便在用户浏览应用时延迟加载它们。这是默认设置,推荐用于大多数场景。

    ¥If 'split', splits the app up into multiple .js/.css files so that they are loaded lazily as the user navigates around the app. This is the default, and is recommended for most scenarios.

  • 如果是 'single',则只创建一个 .js 包和一个包含整个应用代码的 .css 文件。

    ¥If 'single', creates just one .js bundle and one .css file containing code for the entire app.

  • 如果是 'inline',则将整个应用的所有 JavaScript 和 CSS 内联到 HTML 中。结果无需服务器即可使用(即你只需在浏览器中打开文件即可)。

    ¥If 'inline', inlines all JavaScript and CSS of the entire app into the HTML. The result is usable without a server (i.e. you can just open the file in your browser).

使用 'split' 时,你还可以通过在 Vite 配置的 build.rollupOptions 中设置 output.experimentalMinChunkSizeoutput.manualChunks 来调整打包行为。

¥When using 'split', you can also adjust the bundling behaviour by setting output.experimentalMinChunkSize and output.manualChunks inside your Vite config’s build.rollupOptions.

如果你想内联你的资源,你需要将 Vite 的 build.assetsInlineLimit 选项设置为适当的大小,然后通过 Vite 导入你的资源。

¥If you want to inline your assets, you’ll need to set Vite’s build.assetsInlineLimit option to an appropriate size then import your assets through Vite.

vite.config
import { function sveltekit(): Promise<Plugin<any>[]>

Returns the SvelteKit Vite plugins.

sveltekit
} from '@sveltejs/kit/vite';
import { function defineConfig(config: UserConfig): UserConfig (+3 overloads)

Type helper to make it easier to use vite.config.ts accepts a direct {@link UserConfig } object, or a function that returns it. The function receives a {@link ConfigEnv } object.

defineConfig
} from 'vite';
export default function defineConfig(config: UserConfig): UserConfig (+3 overloads)

Type helper to make it easier to use vite.config.ts accepts a direct {@link UserConfig } object, or a function that returns it. The function receives a {@link ConfigEnv } object.

defineConfig
({
UserConfig.plugins?: PluginOption[] | undefined

Array of vite plugins to use.

plugins
: [function sveltekit(): Promise<Plugin<any>[]>

Returns the SvelteKit Vite plugins.

sveltekit
()],
UserConfig.build?: BuildOptions | undefined

Build specific options

build
: {
// inline all imported assets BuildOptions.assetsInlineLimit?: number | ((filePath: string, content: Buffer) => boolean | undefined) | undefined

Static asset files smaller than this number (in bytes) will be inlined as base64 strings. Default limit is 4096 (4 KiB). Set to 0 to disable.

@default4096
assetsInlineLimit
: var Infinity: numberInfinity
} });
src/routes/+layout
<script>
	// import the asset through Vite
	import favicon from './favicon.png';
</script>

<svelte:head>
	<!-- this asset will be inlined as a base64 URL -->
	<link rel="icon" href={favicon} />
</svelte:head>
<script lang="ts">
	// import the asset through Vite
	import favicon from './favicon.png';
</script>

<svelte:head>
	<!-- this asset will be inlined as a base64 URL -->
	<link rel="icon" href={favicon} />
</svelte:head>

paths

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.

base?: '' | `/${string}`;
  • 默认 ""

    ¥default ""

必须以 /(例如 /base-path)开头但不能以 / 结尾的根相对路径,除非它是空字符串。这指定了你的应用的提供服务位置,并允许应用存在于非根路径上。请注意,你需要在所有根相关链接前面添加基值,否则它们将指向你的域的根目录,而不是你的 base(这是浏览器的工作方式)。你可以将 $app/paths 中的 base 用于此目的:<a href="{base}/your-page">Link</a>。如果你发现自己经常写这个,那么将其提取到可重用的组件中可能很有意义。

¥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 for that: <a href="{base}/your-page">Link</a>. If you find yourself writing this often, it may make sense to extract this into a reusable component.

relative?: boolean;
  • 默认 true

    ¥default true

  • v1.9.0 起可用

    ¥available since v1.9.0

是否使用相对资源路径。

¥Whether to use relative asset paths.

如果是 true,从 $app/paths 导入的 baseassets 将在服务器端渲染期间被替换为相对资源路径,从而产生更易于移植的 HTML。如果是 false%sveltekit.assets% 和对构建工件的引用将始终是根相对路径,除非 paths.assets 是外部 URL

¥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 fallback pages will always use absolute paths, regardless of this setting.

如果你的应用使用 <base> 元素,你应该将其设置为 false,否则资源 URL 将错误地根据 <base> URL 而不是当前页面进行解析。

¥If your app uses a <base> element, you should set this to false, otherwise asset URLs will incorrectly be resolved against the <base> URL rather than the current page.

在 1.0 中,undefined 是一个有效值,默认情况下设置。在这种情况下,如果 paths.assets 不是外部的,SvelteKit 会用相对路径替换 %sveltekit.assets%,并使用相对路径引用构建工件,但从 $app/paths 导入的 baseassets 将按照你的配置中指定的方式进行。

¥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.

concurrency?: number;
  • 默认 1

    ¥default 1

可以同时预渲染多少个页面。JS 是单线程的,但在预渲染性能受网络限制的情况下(例如从远程 CMS 加载内容),这可以通过在等待网络响应时处理其他任务来加快速度。

¥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.

crawl?: boolean;
  • 默认 true

    ¥default true

SvelteKit 是否应通过跟踪 entries 中的链接来查找要预渲染的页面。

¥Whether SvelteKit should find pages to prerender by following links from entries.

entries?: var Array: ArrayConstructorArray<'*' | `/${string}`>;
  • 默认 ["*"]

    ¥default ["*"]

要预渲染或开始抓取的页面数组(如果是 crawl: true)。* 字符串包括所有不包含必需 [parameters] 的路由,其中​​包含的可选参数为空(因为 SvelteKit 不知道任何参数应该具有什么值)。

¥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).

handleHttpError?: PrerenderHttpErrorHandlerValue;
  • 默认 "fail"

    ¥default "fail"

  • v1.15.7 起可用

    ¥available since v1.15.7

如何响应预渲染应用时遇到的 HTTP 错误。

¥How to respond to HTTP errors encountered while prerendering the app.

  • 'fail' — 构建失败

    ¥'fail' — fail the build

  • 'ignore' - 默默忽略失败并继续

    ¥'ignore' - silently ignore the failure and continue

  • 'warn' — 继续,但打印警告

    ¥'warn' — continue, but print a warning

  • (details) => void — 自定义错误处理程序,采用具有 statuspathreferrerreferenceTypemessage 属性的 details 对象。如果你从此功能 throw,则构建将失败

    ¥(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

svelte.config
/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        prerender: {
 handleHttpError: ({ path, referrer, message }: {
   path: any;
   referrer: any;
     message: any;
 }) => void;
        };
    };
}
@type{import('@sveltejs/kit').Config}
config
= {
kit: {
    prerender: {
        handleHttpError: ({ path, referrer, message }: {
 path: any;
 referrer: any;
 message: any;
        }) => void;
    };
}
kit
: {
prerender: {
    handleHttpError: ({ path, referrer, message }: {
        path: any;
        referrer: any;
        message: any;
    }) => void;
}
prerender
: {
handleHttpError: ({ path, referrer, message }: {
    path: any;
    referrer: any;
    message: any;
}) => void
handleHttpError
: ({ path: anypath, referrer: anyreferrer, message: anymessage }) => {
// ignore deliberate link to shiny 404 page if (path: anypath === '/not-found' && referrer: anyreferrer === '/blog/how-we-built-our-404-page') { return; } // otherwise fail the build throw new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
(message: anymessage);
} } } };
handleMissingId?: PrerenderMissingIdHandlerValue;
  • 默认 "fail"

    ¥default "fail"

  • v1.15.7 起可用

    ¥available since v1.15.7

当从一个预渲染页面到另一个预渲染页面的哈希链接与目标页面上的 id 不对应时,如何响应。

¥How to respond when hash links from one prerendered page to another don’t correspond to an id on the destination page.

  • 'fail' — 构建失败

    ¥'fail' — fail the build

  • 'ignore' - 默默忽略失败并继续

    ¥'ignore' - silently ignore the failure and continue

  • 'warn' — 继续,但打印警告

    ¥'warn' — continue, but print a warning

  • (details) => void — 自定义错误处理程序,采用具有 pathidreferrersmessage 属性的 details 对象。如果你从此功能 throw,则构建将失败

    ¥(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

handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;
  • 默认 "fail"

    ¥default "fail"

  • v1.16.0 起可用

    ¥available since v1.16.0

entries 导出生成的条目与其生成的路由不匹配时如何响应。

¥How to respond when an entry generated by the entries export doesn’t match the route it was generated from.

  • 'fail' — 构建失败

    ¥'fail' — fail the build

  • 'ignore' - 默默忽略失败并继续

    ¥'ignore' - silently ignore the failure and continue

  • 'warn' — 继续,但打印警告

    ¥'warn' — continue, but print a warning

  • (details) => void — 自定义错误处理程序,采用具有 generatedFromIdentrymatchedIdmessage 属性的 details 对象。如果你从此功能 throw,则构建将失败

    ¥(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

var origin: stringorigin?: string;
  • 默认 "http://sveltekit-prerender"

    ¥default "http://sveltekit-prerender"

预渲染期间 url.origin 的值;如果它包含在渲染的内容中,则很有用。

¥The value of url.origin during prerendering; useful if it is included in rendered content.

router

type?: 'pathname' | 'hash';
  • 默认 "pathname"

    ¥default "pathname"

  • v2.14.0 起可用

    ¥available since v2.14.0

使用哪种类型的客户端路由。

¥What type of client-side router to use.

  • 'pathname' 是默认值,表示当前 URL 路径名决定路由

    ¥'pathname' is the default and means the current URL pathname determines the route

  • 'hash' 表示路由由 location.hash 确定。在这种情况下,SSR 和预渲染被禁用。仅当 pathname 不是一种选择时才建议这样做,例如因为你无法控制部署应用的 Web 服务器。它有一些注意事项:你不能使用服务器端渲染(或任何服务器逻辑),并且你必须确保应用中的链接都以 #/ 开头,否则它们将不起作用。除此之外,一切都与普通的 SvelteKit 应用完全一样。

    ¥'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.

resolution?: 'client' | 'server';
  • 默认 "client"

    ¥default "client"

  • v2.17.0 起可用

    ¥available since v2.17.0

如何确定导航到新页面时要加载哪个路由。

¥How to determine which route to load when navigating to a new page.

默认情况下,SvelteKit 将向浏览器提供路由清单。导航时,此清单用于(如果存在,则与 reroute 钩子一起使用)确定要加载哪些组件以及要运行哪些 load 函数。因为一切都发生在客户端,所以这个决定可以立即做出。缺点是,在第一次导航之前需要加载和解析清单,如果你的应用包含许多路由,这可能会产生影响。

¥By default, SvelteKit will serve a route manifest to the browser. When navigating, this manifest is used (along with the reroute hook, if it exists) to determine which components to load and which load functions to run. Because everything happens on the client, this decision can be made immediately. The drawback is that the manifest needs to be loaded and parsed before the first navigation can happen, which may have an impact if your app contains many routes.

或者,SvelteKit 可以确定服务器上的路由。这意味着对于每个尚未访问过的路径的导航,都会要求服务器确定路由。这有几个优点:

¥Alternatively, SvelteKit can determine the route on the server. This means that for every navigation to a path that has not yet been visited, the server will be asked to determine the route. This has several advantages:

  • 客户端不需要预先加载路由清单,这可以加快初始页面加载速度

    ¥The client does not need to load the routing manifest upfront, which can lead to faster initial page loads

  • 路由列表对公众隐藏

    ¥The list of routes is hidden from public view

  • 服务器有机会拦截每个导航(例如通过中间件),从而启用(例如)对 SvelteKit 不透明的 A/B 测试

    ¥The server has an opportunity to intercept each navigation (for example through a middleware), enabling (for example) A/B testing opaque to SvelteKit

缺点是对于未访问的路径,解析将花费更长的时间(尽管 preloading 可以缓解这种情况)。

¥The drawback is that for unvisited paths, resolution will take slightly longer (though this is mitigated by preloading).

使用服务器端路由解析和预渲染时,解析将与路由本身一起预渲染。

¥[!NOTE] When using server-side route resolution and prerendering, the resolution is prerendered along with the route itself.

serviceWorker

register?: boolean;
  • 默认 true

    ¥default true

是否自动注册服务工作者(如果存在)。

¥Whether to automatically register the service worker, if it exists.

files?(filepath: stringfilepath: string): boolean;
  • 默认 (filename) => !/\.DS_Store/.test(filename)

    ¥default (filename) => !/\.DS_Store/.test(filename)

确定 static 目录中的哪些文件将在 $service-worker.files 中可用。

¥Determine which files in your static directory will be available in $service-worker.files.

typescript

config?: (config: Record<string, any>config: type Record<K extends keyof any, T> = { [P in K]: T; }

Construct a type with a set of properties K of type T

Record
<string, any>) => Record<string, any> | void;
  • 默认 (config) => config

    ¥default (config) => config

  • v1.3.0 起可用

    ¥available since v1.3.0

允许你编辑生成的 tsconfig.json 的函数。你可以改变配置(推荐)或返回新配置。例如,这对于在 monorepo 根中扩展共享 tsconfig.json 很有用。

¥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

如果在人们使用应用时部署新版本,客户端导航可能会出现错误。如果新页面的代码已加载,则可能包含过时的内容;如果不是,应用的路由清单可能会指向不再存在的 JavaScript 文件。SvelteKit 可帮助你通过版本管理解决此问题。如果 SvelteKit 在加载页面时遇到错误并检测到已部署新版本(使用此处指定的 name,默认为构建的时间戳),它将恢复到传统的全页导航。并非所有元素都有专用的类型定义。如果你仍然想在这些情况下强制进行全页导航,请使用设置 pollInterval 然后使用 beforeNavigate 等技术:

¥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:

+layout
<script>
	import { beforeNavigate } from '$app/navigation';
	import { updated } from '$app/state';

	beforeNavigate(({ willUnload, to }) => {
		if (updated.current && !willUnload && to?.url) {
			location.href = to.url.href;
		}
	});
</script>

如果你将 pollInterval 设置为非零值,SvelteKit 将在后台轮询新版本,并在检测到新版本时设置 updated.current true 的值。

¥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 true when it detects one.

const name: void
@deprecated
name
?: string;

当前应用版本字符串。如果指定,这必须是确定性的(例如提交引用而不是 Math.random()Date.now().toString()),否则默认为构建的时间戳。

¥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.

例如,要使用当前提交哈希,你可以使用 git rev-parse HEAD

¥For example, to use the current commit hash, you could do use git rev-parse HEAD:

svelte.config
import * as module "node:child_process"child_process from 'node:child_process';

export default {
	
kit: {
    version: {
        name: string;
    };
}
kit
: {
version: {
    name: string;
}
version
: {
name: stringname: module "node:child_process"child_process.function execSync(command: string): Buffer (+3 overloads)

The child_process.execSync() method is generally identical to {@link exec } with the exception that the method will not return until the child process has fully closed. When a timeout has been encountered and killSignal is sent, the method won’t return until the process has completely exited. If the child process intercepts and handles the SIGTERM signal and doesn’t exit, the parent process will wait until the child process has exited.

If the process times out or has a non-zero exit code, this method will throw. The Error object will contain the entire result from {@link spawnSync } .

Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.

@sincev0.11.12
@paramcommand The command to run.
@returnThe stdout from the command.
execSync
('git rev-parse HEAD').Buffer.toString(encoding?: BufferEncoding, start?: number, end?: number): string

Decodes buf to a string according to the specified character encoding inencoding. start and end may be passed to decode only a subset of buf.

If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8, then each invalid byte is replaced with the replacement character U+FFFD.

The maximum length of a string instance (in UTF-16 code units) is available as {@link constants.MAX_STRING_LENGTH } .

import { Buffer } from 'node:buffer';

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i &#x3C; 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5));
// Prints: abcde

const buf2 = Buffer.from('tést');

console.log(buf2.toString('hex'));
// Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3));
// Prints: té
console.log(buf2.toString(undefined, 0, 3));
// Prints: té
@sincev0.1.90
@paramencoding The character encoding to use.
@paramstart The byte offset to start decoding at.
@paramend The byte offset to stop decoding at (not inclusive).
toString
().String.trim(): string

Removes the leading and trailing white space and line terminator characters from a string.

trim
()
} } };
pollInterval?: number;
  • 默认 0

    ¥default 0

轮询版本更改的间隔(以毫秒为单位)。如果这是 0,则不会发生轮询。

¥The interval in milliseconds to poll for version changes. If this is 0, no polling occurs.

上一页 下一页