编写适配器
如果您的首选环境还没有适配器,您可以自己构建一个。我们建议查看类似平台的适配器源代码,并将其作为起点进行复制。
适配器包实现了以下 API,它创建了一个 Adapter
/** @param {AdapterSpecificOptions} options */
export default function (options: anyoptions) {
/** @type {import('@sveltejs/kit').Adapter} */
const const adapter: Adapteradapter = {
Adapter.name: stringThe 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.
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
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: Adapteradapter;
}其中,name 和 adapt 是必需的。emulate 和 supports 是可选的。
在 adapt 方法中,适配器应该执行一些操作
- 清除构建目录
- 使用
builder.writeClient、builder.writeServer和builder.writePrerendered编写 SvelteKit 输出 - 输出代码,该代码
- 从
${builder.getServerDirectory()}/index.js导入Server - 使用
builder.generateManifest({ relativePath })生成的清单实例化应用程序 - 侦听来自平台的请求,根据需要将其转换为标准的 Request,调用
server.respond(request, { getClientAddress })函数生成 Response 并使用它进行响应 - 通过传递给
server.respond的platform选项,将任何平台特定信息公开给 SvelteKit - 如果需要,全局模拟
fetch以在目标平台上工作。SvelteKit 为可以使用undici的平台提供了@sveltejs/kit/node/polyfills帮助程序
- 从
- 捆绑输出以避免在目标平台上需要安装依赖项(如果需要)。
- 将用户的静态文件和生成的 JS/CSS 放到目标平台的正确位置。
在可能的情况下,我们建议将适配器输出放在 build/ 目录下,并将任何中间输出放在 .svelte-kit/[adapter-name] 下。