跳至主要内容

编写适配器

如果您的首选环境还没有适配器,您可以自己构建一个。我们建议查看类似平台的适配器源代码,并将其作为起点进行复制。

适配器包实现了以下 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 上编辑此页面

上一页 下一页