Skip to main content

Writing adapters

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

适配器包实现了以下 API,该 API 创建了一个适配器

/** @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>) | undefined

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: ({ 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
;
}

在这些中,名称适配是必需的。模拟支持是可选的。

adapt方法中,适配器应该做很多事情:

  • 清理构建目录
  • 编写 SvelteKit 输出,使用builder.writeClientbuilder.writeServerbuilder.writePrerendered
  • 输出代码,使其:
    • 导入 服务器${builder.getServerDirectory()}/index.js
    • 实例化应用程序,使用 builder.generateManifest({ relativePath }) 生成的清单
    • 监听来自平台的请求,如有必要,将其转换为标准 请求,调用 server.respond(request, { getClientAddress }) 函数生成 响应 并以之响应
    • 暴露任何平台特定信息到 SvelteKit,通过传递给 platform 选项的 server.respond
    • 全局适配 fetch 以在目标平台上运行,如有必要。SvelteKit 为可使用 @sveltejs/kit/node/polyfills 的平台提供了一个 undici 帮助器。
  • 将输出打包以避免在目标平台上需要安装依赖项,如果需要
  • 将用户的静态文件和生成的 JS/CSS 放置在目标平台的正确位置

尽可能的情况下,我们建议将适配器输出放在build/目录下,任何中间输出放在.svelte-kit/[adapter-name]目录下。

Edit this page on GitHub llms.txt

previous next