跳至主要內容

設定

您的專案設定位於專案根目錄的 svelte.config.js 檔案中。除了 SvelteKit 之外,此設定物件也供其他與 Svelte 整合的工具(例如編輯器擴充功能)使用。

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

interface Config {}
compilerOptions?: CompileOptions;
  • 預設值 {}

傳遞給 svelte.compile 的選項。

extensions?: string[];
  • 預設值 [".svelte"]

應視為 Svelte 檔案的檔案副檔名清單。

kit?: KitConfig;

SvelteKit 選項

preprocess?: any;

預處理器選項(若有的話)。預處理也可以透過 Vite 的預處理器功能來完成。

vitePlugin?: PluginOptions;

vite-plugin-svelte 外掛程式選項。

[key: string]: any;

與 Svelte 整合的工具所需的任何其他選項。

KitConfig

kit 屬性配置 SvelteKit,可以有以下屬性

adapter

  • 預設值 undefined

您的 adapter 會在執行 vite build 時執行。它決定如何轉換不同平台的輸出。

alias

  • 預設值 {}

一個物件,包含零個或多個別名,用於取代 import 陳述式中的值。這些別名會自動傳遞給 Vite 和 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 控制,因為它用於封裝。

您需要執行 npm run dev 才能讓 SvelteKit 在 jsconfig.jsontsconfig.json 中自動產生所需的別名設定。

appDir

  • 預設值 "_app"

SvelteKit 保存其內容(包括靜態資源(例如 JS 和 CSS)和內部使用的路由)的目錄。

如果指定了 paths.assets,則會有兩個應用程式目錄 — ${paths.assets}/${appDir}${paths.base}/${appDir}

csp

內容安全策略 設定。CSP 透過限制資源載入的位置,協助保護您的使用者免於跨網站指令碼 (XSS) 攻擊。例如,像這樣的設定...

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 會使用它產生的任何內嵌樣式和指令碼的 nonce 或雜湊(取決於 mode)來擴增指定的指令。

若要為 src/app.html 中手動包含的指令碼和連結新增 nonce,您可以使用預留位置 %sveltekit.nonce%(例如 <script nonce="%sveltekit.nonce%">)。

當頁面預先呈現時,CSP 標頭會透過 <meta http-equiv> 標籤新增(請注意,在這種情況下,frame-ancestorsreport-urisandbox 指令將會被忽略)。

mode'auto' 時,SvelteKit 會將 nonce 用於動態呈現的頁面,並將雜湊用於預先呈現的頁面。將 nonce 用於預先呈現的頁面是不安全的,因此禁止使用。

請注意,大多數 Svelte 過渡 的運作方式是建立一個內嵌的 <style> 元素。如果您在應用程式中使用這些,則必須將 style-src 指令保持未指定狀態或新增 unsafe-inline

如果此設定層級不足,而且您有更多動態需求,則可以使用 handle hook 來推出您自己的 CSP。

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

是否使用雜湊或 nonce 來限制 <script><style> 元素。'auto' 會將雜湊用於預先呈現的頁面,並將 nonce 用於動態呈現的頁面。

directives?: CspDirectives;

將會新增至 Content-Security-Policy 標頭的指令。

reportOnly?: CspDirectives;

將會新增至 Content-Security-Policy-Report-Only 標頭的指令。

csrf

防禦跨網站請求偽造 (CSRF) 攻擊。

checkOrigin?: boolean;
  • 預設值 true

是否檢查傳入的 origin 標頭是否為 POSTPUTPATCHDELETE 表單提交,並驗證它是否與伺服器的 origin 相符。

若要允許人們使用 Content-Typeapplication/x-www-form-urlencodedmultipart/form-datatext/plain 從其他 origin 對您的應用程式進行 POSTPUTPATCHDELETE 請求,您將需要停用此選項。請小心!

embedded

  • 預設值 false

應用程式是否嵌入在較大的應用程式中。如果為 true,SvelteKit 會在其父系(而非 window)的 %sveltekit.body% 上新增其與導覽等相關的事件接聽器,並從伺服器傳遞 params,而不是從 location.pathname 推斷它們。請注意,通常不支援在同一頁面上嵌入多個 SvelteKit 應用程式,並在其中使用用戶端 SvelteKit 功能(例如推送到歷程狀態,這假定為單一實例)。

env

環境變數設定

dir?: string;
  • 預設值 "."

要搜尋 .env 檔案的目錄。

publicPrefix?: string;
  • 預設值 "PUBLIC_"

指出環境變數可以安全地暴露給用戶端程式碼的前置字元。請參閱 $env/static/public$env/dynamic/public。請注意,如果您使用的是 Vite 的環境變數處理,則必須單獨設定 Vite 的 envPrefix,不過通常不需要使用該功能。

privatePrefix?: string;
  • 預設值 ""
  • 自版本 v1.21.0 起可用

指出環境變數不安全暴露給用戶端程式碼的前置字元。與公開或私有前置字元都不符的環境變數將會被完全捨棄。請參閱 $env/static/private$env/dynamic/private

files

在您的專案中尋找各種檔案的位置。

assets?: string;
  • 預設值 "static"

放置應具有穩定 URL 且不經過任何處理的靜態檔案(例如 favicon.icomanifest.json)的位置

hooks?: {}
client?: string;
  • 預設值 "src/hooks.client"

您的用戶端 hooks 的位置。

server?: string;
  • 預設值 "src/hooks.server"

您的伺服器 hooks 的位置。

universal?: string;
  • 預設值 "src/hooks"
  • 自版本 v2.3.0 起可用

您的通用 hooks 的位置。

lib?: string;
  • 預設值 "src/lib"

您的應用程式的內部程式庫,在整個程式碼庫中可以作為 $lib 存取

params?: string;
  • 預設值 "src/params"

包含參數比對器的目錄

routes?: string;
  • 預設值 "src/routes"

定義應用程式結構的檔案(請參閱路由

serviceWorker?: string;
  • 預設值 "src/service-worker"

您的 service worker 的進入點位置(請參閱Service workers

appTemplate?: string;
  • 預設值 "src/app.html"

HTML 回應範本的位置

errorTemplate?: string;
  • 預設值 "src/error.html"

後備錯誤回應範本的位置

inlineStyleThreshold

  • 預設值 0

在 HTML 頁首的 <style> 區塊中使用內嵌 CSS。此選項是一個數字,指定要內嵌的 CSS 檔案的最大長度,以 UTF-16 碼元為單位,如同 String.length 屬性所指定。頁面所需且小於此值的所有 CSS 檔案會合併並內嵌在 <style> 區塊中。

這樣可以減少初始請求的次數,並改善你的「首次內容繪製 (First Contentful Paint)」分數。然而,它會產生較大的 HTML 輸出,並降低瀏覽器快取的效率。請謹慎使用。

moduleExtensions

  • 預設值 [".js", ".ts"]

SvelteKit 將視為模組的檔案副檔名陣列。副檔名不符合 config.extensionsconfig.kit.moduleExtensions 的檔案將會被路由器忽略。

outDir

  • 預設值 ".svelte-kit"

SvelteKit 在 devbuild 期間寫入檔案的目錄。您應將此目錄排除在版本控制之外。

output

與建置輸出格式相關的選項

preloadStrategy?: 'modulepreload' | 'preload-js' | 'preload-mjs';
  • 預設值 "modulepreload"
  • 自版本 v1.8.4 起可用

SvelteKit 將預先載入初始頁面所需的 JavaScript 模組,以避免導入「瀑布」,從而加快應用程式啟動速度。有三種策略,其取捨各不相同

  • modulepreload - 使用 <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 中重複解析。某些靜態網路伺服器無法使用 Content-Type: application/javascript 標頭提供 .mjs 檔案,這將導致您的應用程式中斷。如果這不適用於您,這是為最多使用者提供最佳效能的選項,直到 modulepreload 得到更廣泛的支援。

paths

assets?: '' | `http://${string}` | `https://${string}`;
  • 預設值 ""

您的應用程式檔案所服務的絕對路徑。如果您的檔案是從某種儲存桶提供的,這會很有用。

base?: '' | `/${string}`;
  • 預設值 ""

一個根目錄相對路徑,必須以 / 開始,但不能以 / 結束(例如 /base-path),除非它是空字串。這指定您的應用程式從哪裡提供服務,並允許應用程式存在於非根路徑上。請注意,您需要將所有根目錄相對連結加上基本值的前綴,否則它們將指向您網域的根目錄,而不是您的 base(這是瀏覽器的工作方式)。您可以使用 來自 $app/pathsbase 來執行此操作:<a href="{base}/your-page">Link</a>。如果您發現自己經常撰寫此程式碼,則將其提取到可重複使用的元件中可能是有意義的。

relative?: boolean;
  • 預設值 true
  • 自版本 v1.9.0 起可用

是否使用相對資源路徑。

如果為 true,則從 $app/paths 匯入的 baseassets 將在伺服器端渲染期間替換為相對資源路徑,從而產生更可攜的 HTML。如果為 false,則 %sveltekit.assets% 和對建置產物的引用將始終是根目錄相對路徑,除非 paths.assets 是外部 URL

單頁應用程式 回退頁面將始終使用絕對路徑,無論此設定如何。

如果您的應用程式使用 <base> 元素,則應將此設定為 false,否則資源 URL 將錯誤地根據 <base> URL 而非目前頁面進行解析。

在 1.0 版中,undefined 是一個有效值,預設為該值。在這種情況下,如果 paths.assets 不是外部的,則 SvelteKit 會將 %sveltekit.assets% 替換為相對路徑,並使用相對路徑來引用建置產物,但是從 $app/paths 匯入的 baseassets 將按照您配置中指定的方式。

prerender

請參閱 預先渲染

concurrency?: number;
  • 預設值 1

可以同時預先渲染多少頁面。JS 是單執行緒的,但是在預先渲染效能受網路約束的情況下(例如從遠端 CMS 載入內容),這可以在等待網路回應時處理其他任務來加快速度。

crawl?: boolean;
  • 預設值 true

SvelteKit 是否應透過追蹤 entries 中的連結來尋找要預先渲染的頁面。

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

要預先渲染的頁面陣列,或開始爬網的頁面(如果 crawl: true)。* 字串包含所有不含必要 [parameters] 的路由,其中可選參數視為空(因為 SvelteKit 不知道任何參數應具有的值)。

handleHttpError?: PrerenderHttpErrorHandlerValue;
  • 預設值 "fail"
  • 自版本 v1.15.7 起可用

在預先渲染應用程式時遇到 HTTP 錯誤時的回應方式。

  • 'fail' — 建置失敗
  • 'ignore' - 靜默忽略失敗並繼續
  • 'warn' — 繼續,但列印警告
  • (details) => void — 一個自訂錯誤處理常式,它接收一個具有 statuspathreferrerreferenceTypemessage 屬性的 details 物件。如果您從此函數中 throw,建置將會失敗
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"
  • 自版本 v1.15.7 起可用

當從一個預先渲染的頁面到另一個頁面的雜湊連結與目標頁面上的 id 不符時的回應方式。

  • 'fail' — 建置失敗
  • 'ignore' - 靜默忽略失敗並繼續
  • 'warn' — 繼續,但列印警告
  • (details) => void — 一個自訂錯誤處理常式,它接收一個具有 pathidreferrersmessage 屬性的 details 物件。如果您從此函數中 throw,建置將會失敗
handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;
  • 預設值 "fail"
  • 自版本 v1.16.0 起可用

entries 匯出產生的項目與產生它的路由不符時的回應方式。

  • 'fail' — 建置失敗
  • 'ignore' - 靜默忽略失敗並繼續
  • 'warn' — 繼續,但列印警告
  • (details) => void — 一個自訂錯誤處理常式,它接收一個具有 generatedFromIdentrymatchedIdmessage 屬性的 details 物件。如果您從此函數中 throw,建置將會失敗
var origin: stringorigin?: string;
  • 預設值 "http://sveltekit-prerender"

預先渲染期間 url.origin 的值;如果它包含在渲染的內容中,則很有用。

serviceWorker

register?: boolean;
  • 預設值 true

是否自動註冊 service worker(如果存在)。

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;
  • 預設值 (config) => config
  • 自版本 v1.3.0 起可用

一個允許您編輯產生的 tsconfig.json 的函數。您可以變更配置(建議)或傳回新的配置。例如,這對於擴展單一儲存庫根目錄中的共用 tsconfig.json 很有用。

version

如果在人們使用您的應用程式時部署新版本的應用程式,用戶端導航可能會出現錯誤。如果新頁面的程式碼已載入,則它可能具有過時的內容;如果沒有載入,則應用程式的路由清單可能指向不再存在的 JavaScript 檔案。SvelteKit 透過版本管理來協助您解決此問題。如果 SvelteKit 在載入頁面時遇到錯誤,並偵測到已部署新版本(使用此處指定的 name,預設為建置的時間戳記),它將會回退到傳統的完整頁面導航。並非所有導航都會導致錯誤,例如,如果下一個頁面的 JavaScript 已載入。如果您仍然希望在這些情況下強制進行完整頁面導航,請使用設定 pollInterval 然後使用 beforeNavigate 等技術

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

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

如果您將 pollInterval 設定為非零值,SvelteKit 將在背景輪詢新版本,並在偵測到新版本時將 updated 商店的值設定為 true

const name: void
@deprecated
name
?: string;

目前的應用程式版本字串。如果指定,則它必須是確定性的(例如,提交引用,而不是 Math.random()Date.now().toString()),否則預設為建置的時間戳記。

例如,若要使用目前的提交雜湊,您可以使用 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

輪詢版本變更的間隔(以毫秒為單位)。如果此值為 0,則不會進行輪詢。

在 GitHub 上編輯此頁面

上一頁 下一頁