跳至主要內容

撰寫轉接器

如果您的偏好環境沒有現成的轉接器,您可以自行建置。我們建議查看與您的平台類似的轉接器原始碼,並複製它作為起點。

轉接器套件實作以下 API,以建立一個 Adapter

/** @param {AdapterSpecificOptions} options */
export default function (options: any
@paramoptions
options
) {
/** @type {import('@sveltejs/kit').Adapter} */ const const adapter: Adapter
@type{import('@sveltejs/kit').Adapter}
adapter
= {
Adapter.name: string

The name of the adapter, using for logging. Will typically correspond to the package name.

name
: 'adapter-package-name',
async Adapter.adapt(builder: Builder): MaybePromise<void>

This function is called after SvelteKit has built your app.

@parambuilder An object provided by SvelteKit that contains methods for adapting the app
adapt
(builder: Builderbuilder) {
// adapter implementation }, async Adapter.emulate?(): MaybePromise<Emulator>

Creates an Emulator, which allows the adapter to influence the environment during dev, build and prerendering

emulate
() {
return { async
Emulator.platform?(details: {
    config: any;
    prerender: PrerenderOption;
}): MaybePromise<App.Platform>

A function that is called with the current route config and prerender option and returns an App.Platform object

platform
({ config: anyconfig, prerender: PrerenderOptionprerender }) {
// the returned object becomes `event.platform` during dev, build and // preview. Its shape is that of `App.Platform` } } },
Adapter.supports?: {
    read?: (details: {
        config: any;
        route: {
            id: string;
        };
    }) => boolean;
} | undefined

Checks called during dev and build to determine whether specific features will work in production with this adapter

supports
: {
read?: ((details: {
    config: any;
    route: {
        id: string;
    };
}) => boolean) | undefined

Test support for read from $app/server

@paramconfig The merged route config
read
: ({ config: anyconfig,
route: {
    id: string;
}
route
}) => {
// Return `true` if the route with the given `config` can use `read` // from `$app/server` in production, return `false` if it can't. // Or throw a descriptive error describing how to configure the deployment } } }; return const adapter: Adapter
@type{import('@sveltejs/kit').Adapter}
adapter
;
}

其中,nameadapt 是必要的。emulatesupports 是可選的。

adapt 方法中,轉接器應執行許多操作

  • 清除建置目錄
  • 使用 builder.writeClientbuilder.writeServerbuilder.writePrerendered 寫入 SvelteKit 輸出
  • 輸出程式碼,該程式碼:
    • ${builder.getServerDirectory()}/index.js 匯入 Server
    • 使用 builder.generateManifest({ relativePath }) 產生的清單來實例化應用程式
    • 監聽來自平台的要求,如有必要,將其轉換為標準的 Request,呼叫 server.respond(request, { getClientAddress }) 函式以產生 Response,並使用它回應
    • 透過傳遞給 server.respondplatform 選項,向 SvelteKit 公開任何平台特定的資訊
    • 如有必要,全域地墊片 fetch 以在目標平台上工作。SvelteKit 為可以使用 undici 的平台提供 @sveltejs/kit/node/polyfills 輔助程式
  • 如有必要,將輸出捆綁在一起,以避免需要在目標平台上安裝依賴項
  • 將使用者的靜態檔案和產生的 JS/CSS 放在目標平台的正確位置

如果可以,我們建議將轉接器輸出放在 build/ 目錄下,任何中間輸出放在 .svelte-kit/[adapter-name] 下。

在 GitHub 上編輯此頁面

上一篇 下一篇