Configuration
您的项目配置位于项目根目录下的 svelte.config.js 文件中。此外,SvelteKit 也使用此配置对象,以及其他与 Svelte 集成的工具,如编辑器扩展。
import const adapter: () => import("@sveltejs/kit").Adapteradapter from '@sveltejs/adapter-auto';
/** @type {import('@sveltejs/kit').Config} */
const const config: Configconfig = {
Config.kit?: KitConfig | undefinedSvelteKit options
kit: {
KitConfig.adapter?: Adapter | undefinedYour adapter is run when executing vite build. It determines how the output is converted for different platforms.
adapter: function adapter(): import("@sveltejs/kit").Adapteradapter()
}
};
export default const config: Configconfig;配置
interface Config extends SvelteConfig {…}kit?: KitConfig;SvelteKit 选项。
[键:字符串]: 任何;
任何需要与 Svelte 集成的工具所需的附加选项。
套件配置
The kit 属性配置 SvelteKit,并可以具有以下属性:
适配器
- 默认
未定义
您的适配器在执行vite build时运行。它决定了输出如何转换为不同的平台。
别名
- 默认
{}
一个包含零个或多个别名的对象,用于替换 import 语句中的值。这些别名将自动传递给 Vite 和 TypeScript。
/** @type {import('@sveltejs/kit').Config} */
const const config: {
kit: {
alias: {
'my-file': string;
'my-directory': string;
'my-directory/*': string;
};
};
}
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控制,因为它用于打包。
[!注意] 您需要运行
npm run dev以使 SvelteKit 自动在jsconfig.json或tsconfig.json中生成所需的别名配置。
appDir
- 默认
"_app"
目录,其中 SvelteKit 存储其内容,包括静态资产(如 JS 和 CSS)以及内部使用的路由。
如果指定了 paths.assets,则会有两个应用程序目录 — ${paths.assets}/${appDir} 和 ${paths.base}/${appDir}。
csp
内容安全策略配置。CSP 有助于保护您的用户免受跨站脚本(XSS)攻击,通过限制资源可以加载的位置。例如,这样的配置...
/** @type {import('@sveltejs/kit').Config} */
const const config: {
kit: {
csp: {
directives: {
'script-src': string[];
};
reportOnly: {
'script-src': string[];
'report-uri': string[];
};
};
};
}
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[];
};
};
};
}config;...将阻止从外部站点加载脚本。SvelteKit 将为它生成的任何内联样式和脚本添加非 ces 或散列(取决于模式)以增强指定的指令。
要手动为包含在src/app.html中的脚本和链接添加 nonce,您可以使用占位符%sveltekit.nonce%(例如 <script nonce="%sveltekit.nonce%"> )。
当页面预渲染时,通过一个<meta http-equiv>标签添加 CSP 头部(注意,在这种情况下,frame-ancestors、report-uri和sandbox指令将被忽略)。
[!注意] 当
模式为'自动'时,SvelteKit 将为动态渲染的页面使用非 ces,为预渲染的页面使用哈希。在预渲染的页面中使用非 ces 是不安全的,因此被禁止。
[!注意] 注意,大多数 Svelte 过渡 通过创建一个内联
<style>元素来工作。如果您在您的应用程序中使用这些,您必须保留style-src指令未指定,或者添加unsafe-inline。
如果此级别的配置不足,并且您有更多动态需求,可以使用handle钩子来自定义您的 CSP。
mode?: 'hash' | 'nonce' | 'auto';是否使用哈希或 nonce 来限制<script>和<style>元素。'auto'将为预渲染页面使用哈希,为动态渲染页面使用 nonce。
directives?: CspDirectives;指令将添加到 内容安全策略 头部。
reportOnly?: CspDirectives;指令将添加到 Content-Security-Policy-Report-Only 头中。
csrf
checkOrigin?: boolean;- 默认
真
是否检查 incoming origin 标头对于 POST、PUT、PATCH 或 DELETE 表单提交,并验证其是否与服务器原点匹配。
为了允许人们从其他来源向您的应用发送具有 application/x-www-form-urlencoded Content-Type的POST、PUT、PATCH或DELETE请求,其中multipart/form-data或text/plain,您需要禁用此选项。请小心!
嵌入式
- 默认
否
是或否将应用嵌入到更大的应用中。如果 true,SvelteKit 将在其父元素 %sveltekit.body% 上添加与导航等相关的监听器,而不是添加到 window,并且将从服务器传递 params 而不是从 location.pathname 推断它们。请注意,通常不支持在同一页面上嵌入多个 SvelteKit 应用,并在其中使用客户端 SvelteKit 功能(例如,将历史状态推送到单个实例)。
env
环境变量配置
// @noErrors `没有错误 dir?: 字符串;`
- 默认
“.”
搜索 .env 文件的目录。
publicPrefix?: string;- 默认
"PUBLIC_"
前缀表示环境变量可以安全地暴露给客户端代码。请参阅 $env/static/public 和 $env/dynamic/public。请注意,如果您使用 Vite 的环境变量处理,则必须单独设置 Vite 的 envPrefix,尽管通常不需要使用该功能。
privatePrefix?: string;- 默认
"" - 自 v1.21.0 起可用
前缀表示环境变量不安全,不能暴露给客户端代码。既不匹配公共前缀也不匹配私有前缀的环境变量将被完全丢弃。请参阅$env/static/private和$env/dynamic/private。
文件
在哪里可以找到项目中的各种文件。
assets?: string;- 默认
"静态"
一个存放静态文件的地方,这些文件应具有稳定的 URL 且不经过处理,例如 favicon.ico 或 manifest.json
// @noErrors `没有错误 hooks?: {/*…*/}`
client?: string;- 默认
"src/hooks.client"
您的客户端钩子的位置。
server?: string;- 默认
"src/hooks.server"
您的服务器位置 钩子。
universal?: string;- 默认
"src/钩子" - 自 v2.3.0 起可用
您的通用钩子的位置。
// @noErrors `没有错误 lib?: 字符串;`
- 默认
"src/lib"
您的应用程序的内部库,在整个代码库中可通过$lib访问
params?: string;- 默认
"src/params"
一个包含参数匹配器的目录
routes?: string;- 默认
"src/路由"
文件定义您的应用程序结构(见路由)
serviceWorker?: string;- 默认
"src/service-worker"
服务工作者入口点的位置(见服务工作者)
appTemplate?: string;- 默认
"src/app.html"
模板的位置,用于 HTML 响应
errorTemplate?: string;- 默认
"src/error.html"
模板的回退错误响应位置
行内样式阈值
- 默认
0
行内 CSS 位于 HTML 头部<style>块内。此选项是一个数字,指定 CSS 文件在 UTF-16 代码单元中的最大长度,如String.length属性所述,以行内形式存在。所有小于此值的页面所需的 CSS 文件都将合并并内联到<style>块中。
[注意] 这会导致初始请求更少,并可以提高您的首次内容绘制得分。然而,它会产生更大的 HTML 输出,并降低浏览器缓存的效率。请谨慎使用。
模块扩展
- 默认
[".js", ".ts"]
文件扩展名数组,SvelteKit 将其视为模块。与 config.extensions 或 config.kit.moduleExtensions 不匹配的扩展名文件将被路由器忽略。
输出目录
- 默认
“.svelte-kit”
目录是 SvelteKit 在dev和build期间写入文件的目录。您应该将此目录排除在版本控制之外。
输出
与构建输出格式相关的选项
preloadStrategy?: 'modulepreload' | 'preload-js' | 'preload-mjs';- 默认
"模块预加载" - 自 v1.8.4 起可用
SvelteKit 将预加载初始页面所需的 JavaScript 模块,以避免出现 ‘waterfalls’ 导入,从而实现更快的应用程序启动。这里有三种策略,各有不同的权衡。
模块预加载- 使用<link rel="modulepreload">。在基于 Chromium 的浏览器、Firefox 115+ 和 Safari 17+ 中效果最佳。在较旧浏览器中被忽略。preload-js- 使用<link rel="preload">。防止 Chromium 和 Safari 中的瀑布效应,但 Chromium 会解析每个模块两次(一次作为脚本,一次作为模块)。在 Firefox 中导致模块被请求两次。如果您想最大限度地提高 iOS 设备用户的性能,而以 Chromium 用户性能的轻微下降为代价,这是一个好的设置。preload-mjs- 使用<link rel="preload">但带有.mjs扩展名,这可以防止在 Chromium 中重复解析。一些静态 Web 服务器可能会因为Content-Type: application/javascript头部而无法提供 .mjs 文件,这会导致您的应用程序崩溃。如果这不适合您,这是为最大数量的用户提供最佳性能的选项,直到modulepreload得到更广泛的支持。
bundleStrategy?: 'split' | 'single' | 'inline';- 默认
'split' - 自 v2.13.0 起可用
捆绑策略选项影响您的应用程序的 JavaScript 和 CSS 文件加载方式。
- 如果
'split',则将应用拆分为多个.js/.css 文件,以便在用户在应用中导航时按需加载。这是默认设置,适用于大多数场景。 - 如果
'single',则仅创建一个包含整个应用代码的 .js 包和一个 .css 文件。 - 如果
'inline',则将整个应用的所有 JavaScript 和 CSS 内联到 HTML 中。结果无需服务器即可使用(即您可以直接在浏览器中打开文件)。
当使用'split'时,您还可以通过在您的 Vite 配置的build.rollupOptions中设置 output.experimentalMinChunkSize 和output.manualChunks来调整捆绑行为。
如果您想内联您的资源,您需要将 Vite 的 build.assetsInlineLimit 选项设置为适当的大小,然后通过 Vite 导入您的资源。
import { function sveltekit(): Promise<Plugin$1<any>[]>Returns the SvelteKit Vite plugins.
sveltekit } from '@sveltejs/kit/vite';
import { function defineConfig(config: UserConfig): UserConfig (+5 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 (+5 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[] | undefinedArray of vite plugins to use.
plugins: [function sveltekit(): Promise<Plugin$1<any>[]>Returns the SvelteKit Vite plugins.
sveltekit()],
build?: BuildEnvironmentOptions | undefinedBuild specific options
build: {
// inline all imported assets
BuildEnvironmentOptions.assetsInlineLimit?: number | ((filePath: string, content: Buffer) => boolean | undefined) | undefinedStatic asset files smaller than this number (in bytes) will be inlined as
base64 strings. If a callback is passed, a boolean can be returned to opt-in
or opt-out of inlining. If nothing is returned the default logic applies.
Default limit is 4096 (4 KiB). Set to 0 to disable.
assetsInlineLimit: var Infinity: numberInfinity
}
});<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>路径
assets?: '' | `http://${string}` | `https://${string}`;- 默认
""
绝对路径,您的应用程序文件从中提供的服务路径。如果您的文件是从某种存储桶中提供服务的,这很有用。
base?: '' | `/${string}`;- 默认
""
根相对路径必须以/开头,但不能以/结尾(例如:/base-path),除非它是空字符串。这指定了您的应用程序从哪里提供服务,并允许应用程序存在于非根路径上。请注意,您需要将所有根相对链接都添加基本值作为前缀,否则它们将指向域的根,而不是您的基本(这就是浏览器的工作方式)。您可以使用从$app/paths中的基本:进行此操作: <a href="{base}/your-page">Link</a> 。如果您经常编写此内容,将其提取为可重用组件可能是有意义的。
relative?: boolean;- 默认
真 - 自 v1.9.0 起可用
是否使用相对资源路径。
如果 true,则从 $app/paths 导入的 base 和 assets 在服务器端渲染期间将被替换为相对资产路径,从而生成更易于携带的 HTML。如果 false,则 %sveltekit.assets% 和对构建实体的引用将始终是根相关路径,除非 paths.assets 是外部 URL。
单页应用程序回退页面将始终使用绝对路径,无论此设置如何。
如果您的应用使用了<base>元素,您应该将其设置为false,否则资产 URL 将不正确地相对于<base> URL 解析,而不是当前页面。
在 1.0 版本中,undefined是一个有效的值,默认设置为该值。在这种情况下,如果paths.assets不是外部的,SvelteKit 会将%sveltekit.assets%替换为相对路径,并使用相对路径来引用构建工件,但从$app/paths导入的base和assets将按照您的配置指定。
预渲染
查看预渲染。
concurrency?: number;- 默认
1
一次可以预渲染多少页。JavaScript 是单线程的,但在预渲染性能受网络限制的情况下(例如从远程 CMS 加载内容),这可以通过在等待网络响应时处理其他任务来加快速度。
crawl?: boolean;- 默认
真
是否 SvelteKit 应通过跟随从entries的链接来查找需要预渲染的页面。
entries?: var Array: ArrayConstructorArray<'*' | `/${string}`>;- 默认
["*"]
一個待預渲染的頁面數組,或從此開始爬取(如果 crawl: true)。* 字符串包括所有不包含必需的 [參數] 且選項參數為空的路由(因為 SvelteKit 不清楚任何參數應該有何值)。
handleHttpError?: PrerenderHttpErrorHandlerValue;- 默认
"失败" - 自 v1.15.7 起可用
如何应对在预渲染应用时遇到的 HTTP 错误。
失败— 构建失败忽略- 静默忽略失败并继续警告— 继续执行,但打印警告(详细信息) => void— 一个自定义错误处理器,它接受一个具有状态、路径、来源、引用类型和消息属性的详细信息对象。如果您从这个函数中抛出异常,构建将失败
/** @type {import('@sveltejs/kit').Config} */
const const config: {
kit: {
prerender: {
handleHttpError: ({ path, referrer, message }: {
path: any;
referrer: any;
message: any;
}) => void;
};
};
}
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;- 默认
"失败" - 自 v1.15.7 起可用
如何应对从一个预渲染页面到另一个页面时,哈希链接与目标页面上的 id 不对应的情况。
失败— 构建失败忽略- 静默忽略失败并继续警告— 继续执行,但打印警告(详细信息) => void— 一个自定义错误处理器,它接受一个具有路径、id、引用者和消息属性的详细信息对象。如果您从这个函数中抛出,构建将失败
handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;- 默认
"失败" - 自 v1.16.0 起可用
如何应对由entries导出生成的条目与其生成的路由不匹配的情况。
失败— 构建失败忽略- 静默忽略失败并继续警告— 继续执行,但打印警告(详细信息) => void— 一个自定义错误处理器,它接受一个具有generatedFromId、entry、matchedId和message属性的details对象。如果您从这个函数中throw,构建将失败
var origin: stringorigin?: string;- 默认
"http://sveltekit-prerender"
The value of url.origin during prerendering; useful if it is included in rendered content.
路由器
type?: 'pathname' | 'hash';- 默认
"路径名" - 自 v2.14.0 起可用
使用哪种客户端路由器。
‘pathname’是默认值,表示当前 URL 的路径名决定路由‘hash’表示路由由location.hash决定。在这种情况下,SSR 和预渲染被禁用。只有在pathname不可选时才推荐这样做,例如,因为你无法控制部署应用程序的 web 服务器。它带来了一些注意事项:你不能使用服务器端渲染(或者确实任何服务器逻辑),并且你必须确保你的应用程序中的所有链接都以 #/ 开头,否则它们将无法工作。除此之外,一切工作方式都与正常的 SvelteKit 应用程序完全相同。
resolution?: 'client' | 'server';- 默认
"客户端" - 自 v2.17.0 起可用
如何确定在导航到新页面时加载哪条路由。
默认情况下,SvelteKit 将为浏览器提供路由清单。在导航时,此清单(以及如果存在,则使用reroute钩子)用于确定要加载哪些组件以及要运行哪些load函数。因为所有操作都在客户端进行,所以这个决定可以立即做出。缺点是必须在第一次导航之前加载和解析清单,如果您的应用程序包含许多路由,这可能会产生影响。
或者,SvelteKit 可以在服务器上确定路由。这意味着对于每个导航到尚未访问的路径,服务器将被要求确定路由。这有几个优点:
- 客户端无需预先加载路由清单,这可以导致页面初始加载更快
- 路由列表对公众隐藏
- 服务器有机会拦截每次导航(例如通过中间件),从而实现(例如)对 SvelteKit 不可见的 A/B 测试
缺点是对于未访问的路径,解析将稍微花费更长的时间(尽管这可以通过预加载来缓解)。
[注意] 当使用服务器端路由解析和预渲染时,解析将与路由本身一起预渲染。
服务工作者
register?: boolean;- 默认
真
是否自动注册存在的服务工作者。
files?(filepath: stringfilepath: string): boolean;- 默认
(filename) => !/\.DS_Store/.test(filename)
确定你的 static 目录中哪些文件将在 $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;- 默认
(配置) => 配置 - 自 v1.3.0 起可用
一个允许您编辑生成的tsconfig.json的函数。您可以修改配置(推荐)或返回一个新的配置。这在扩展 monorepo 根目录中的共享tsconfig.json时非常有用。
版本
客户端导航可能会出现 bug,如果您在用户使用应用时部署新版本,如果新页面的代码已经加载,它可能包含过时内容;如果没有加载,应用的路线清单可能指向一个不再存在的 JavaScript 文件。SvelteKit 通过版本管理帮助您解决这个问题。如果 SvelteKit 在加载页面时遇到错误并检测到已部署新版本(使用此处指定的name,默认为构建的时间戳),它将回退到传统的全页导航。并非所有导航都会导致错误,例如,如果下一页的 JavaScript 已经加载。如果您仍然想在这些情况下强制全页导航,请使用设置pollInterval然后使用beforeNavigate等技术。
<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](/docs/kit/$app-state#updated)``true的值设置为。
// @noErrors `没有错误 名称?: 字符串;`
当前应用版本字符串。如果指定,则必须是确定的(例如,提交引用而不是 Math.random() 或 Date.now().toString()),否则默认为构建的时间戳。
例如,要使用当前的提交哈希,您可以这样做:使用 git rev-parse HEAD:
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.
execSync('git rev-parse HEAD').Buffer<ArrayBufferLike>.toString(encoding?: BufferEncoding, start?: number, end?: number): stringDecodes 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 < 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é
toString().String.trim(): stringRemoves the leading and trailing white space and line terminator characters from a string.
trim()
}
}
};pollInterval?: number;- 默认
0
毫秒级的轮询版本更改的间隔。如果这是 0,则不进行轮询。
Edit this page on GitHub llms.txt