Skip to main content

Cloudflare

要部署到 Cloudflare WorkersCloudflare 页面,请使用 adapter-cloudflare

¥To deploy to Cloudflare Workers or Cloudflare Pages, use adapter-cloudflare.

当你使用 adapter-auto 时,此适配器将默认安装。如果你计划继续使用 Cloudflare,你可以从 adapter-auto 切换到直接使用此适配器,以便在本地开发期间模拟 event.platform,自动应用类型声明,并提供设置 Cloudflare 特定选项的功能。

¥This adapter will be installed by default when you use adapter-auto. If you plan on staying with Cloudflare, you can switch from adapter-auto to using this adapter directly so that event.platform is emulated during local development, type declarations are automatically applied, and the ability to set Cloudflare-specific options is provided.

比较(Comparisons)

¥Comparisons

  • adapter-cloudflare - 标签已弃用为 Cloudflare Workers Static Assets 和 Cloudflare Pages 构建

    ¥adapter-cloudflare – supports all SvelteKit features; builds for Cloudflare Workers Static Assets and Cloudflare Pages

  • adapter-cloudflare-workers - 已弃用。支持所有 SvelteKit 功能;为 Cloudflare Workers Sites 构建

    ¥adapter-cloudflare-workers – deprecated. Supports all SvelteKit features; builds for Cloudflare Workers Sites

  • adapter-static - 仅生成客户端静态资源;与 Cloudflare Workers Static Assets 和 Cloudflare Pages 兼容

    ¥adapter-static – only produces client-side static assets; compatible with Cloudflare Workers Static Assets and Cloudflare Pages

用法(Usage)

¥Usage

使用 npm i -D @sveltejs/adapter-cloudflare 安装,然后将适配器添加到你的 svelte.config.js

¥Install with npm i -D @sveltejs/adapter-cloudflare, then add the adapter to your svelte.config.js:

svelte.config
import import adapteradapter from '@sveltejs/adapter-cloudflare';

export default {
	
kit: {
    adapter: any;
}
kit
: {
adapter: anyadapter: import adapteradapter({ // See below for an explanation of these options config: undefinedconfig: var undefinedundefined,
platformProxy: {
    configPath: undefined;
    environment: undefined;
    persist: undefined;
}
platformProxy
: {
configPath: undefinedconfigPath: var undefinedundefined, environment: undefinedenvironment: var undefinedundefined, persist: undefinedpersist: var undefinedundefined }, fallback: stringfallback: 'plaintext',
routes: {
    include: string[];
    exclude: string[];
}
routes
: {
include: string[]include: ['/*'], exclude: string[]exclude: ['<all>'] } }) } };

选项(Options)

¥Options

config

Wrangler 配置文件 的路径。如果你想使用 wrangler.jsoncwrangler.jsonwrangler.toml 以外的 Wrangler 配置文件名,可以使用此选项指定。

¥Path to your Wrangler configuration file. If you would like to use a Wrangler configuration filename other than wrangler.jsonc, wrangler.json, or wrangler.toml you can specify it using this option.

platformProxy

模拟 platform.env 本地绑定的首选项。有关完整选项列表,请参阅 getPlatformProxy Wrangler API 文档。

¥Preferences for the emulated platform.env local bindings. See the getPlatformProxy Wrangler API documentation for a full list of options.

fallback

对于不匹配的资源请求,是否渲染纯文本 404.html 页面或渲染的 SPA 回退页面。

¥Whether to render a plaintext 404.html page or a rendered SPA fallback page for non-matching asset requests.

对于 Cloudflare Workers,默认行为是针对不匹配资源的请求返回一个空主体 404 状态响应。但是,如果 assets.not_found_handling Wrangler 配置设置为 "404-page",则当请求与资源匹配失败时,将提供此页面。如果 assets.not_found_handling 设置为 "single-page-application",则无论 fallback 选项是否指定,适配器都会渲染 SPA 回退 index.html 页面。

¥For Cloudflare Workers, the default behaviour is to return a null-body 404-status response for non-matching assets requests. However, if the assets.not_found_handling Wrangler configuration setting is set to "404-page", this page will be served if a request fails to match an asset. If assets.not_found_handling is set to "single-page-application", the adapter will render a SPA fallback index.html page regardless of the fallback option specified.

对于 Cloudflare Pages,仅当与 routes.exclude 中的条目匹配的请求与资源匹配失败时,才会提供此页面。

¥For Cloudflare Pages, this page will only be served when a request that matches an entry in routes.exclude fails to match an asset.

大多数情况下,plaintext 就足够了,但如果你使用 routes.exclude 手动排除一组预渲染页面,且不超过 100 条路由的限制,则可能希望使用 spa,以避免向用户显示无样式的 404 页面。

¥Most of the time plaintext is sufficient, but if you are using routes.exclude to manually exclude a set of prerendered pages without exceeding the 100 route limit, you may wish to use spa instead to avoid showing an unstyled 404 page to users.

有关更多信息,请参阅 Cloudflare Pages 的 未找到行为

¥See Cloudflare Pages’ Not Found behaviour for more info.

routes

仅适用于 Cloudflare Pages。允许你自定义由 adapter-cloudflare 生成的 _routes.json 文件。

¥Only for Cloudflare Pages. Allows you to customise the _routes.json file generated by adapter-cloudflare.

  • include 定义将调用函数的路由,默认为 ['/*']

    ¥include defines routes that will invoke a function, and defaults to ['/*']

  • exclude 定义不会调用函数的路由 - 这是为你的应用的静态资源提供服务的更快、更便宜的方式。此数组可以包含以下特殊值:

    ¥exclude defines routes that will not invoke a function — this is a faster and cheaper way to serve your app’s static assets. This array can include the following special values:

    • <build> 包含你的应用的构建工件(由 Vite 生成的文件)

      ¥<build> contains your app’s build artifacts (the files generated by Vite)

    • <files> 包含你的 static 目录的内容

      ¥<files> contains the contents of your static directory

    • <prerendered> 包含预渲染页面列表

      ¥<prerendered> contains a list of prerendered pages

    • <all>(默认)包含以上所有内容

      ¥<all> (the default) contains all of the above

你最多可​​以组合 100 条 includeexclude 规则。通常,你可以省略 routes 选项,但如果(例如)你的 <prerendered> 路径超出该限制,你可能会发现手动创建包含 '/articles/*'exclude 列表(而不是自动生成的 ['/articles/foo', '/articles/bar', '/articles/baz', ...])会很有帮助。

¥You can have up to 100 include and exclude rules combined. Generally you can omit the routes options, but if (for example) your <prerendered> paths exceed that limit, you may find it helpful to manually create an exclude list that includes '/articles/*' instead of the auto-generated ['/articles/foo', '/articles/bar', '/articles/baz', ...].

Cloudflare Workers

基本配置(Basic configuration)

¥Basic configuration

为 Cloudflare Workers 构建时,此适配器需要在项目根目录中找到 Wrangler 配置文件。它看起来应该像这样:

¥When building for Cloudflare Workers, this adapter expects to find a Wrangler configuration file in the project root. It should look something like this:

wrangler
{
	"name": "<any-name-you-want>",
	"main": ".svelte-kit/cloudflare/_worker.js",
	"compatibility_date": "2025-01-01",
	"assets": {
		"binding": "ASSETS",
		"directory": ".svelte-kit/cloudflare",
	}
}

部署(Deployment)

¥Deployment

请遵循 Cloudflare Workers 的 框架指南 开始操作。

¥Please follow the framework guide for Cloudflare Workers to begin.

Cloudflare 页面(Cloudflare Pages)

¥Cloudflare Pages

部署(Deployment)

¥Deployment

请按照 Cloudflare 页面的 入门指南 开始。

¥Please follow the Get Started Guide for Cloudflare Pages to begin.

如果你使用的是 Git 集成,你的构建设置应如下所示:

¥If you’re using the Git integration, your build settings should look like this:

  • 框架预设 – SvelteKit

    ¥Framework preset – SvelteKit

  • 构建命令 - npm run buildvite build

    ¥Build commandnpm run build or vite build

  • 构建输出目录 - .svelte-kit/cloudflare

    ¥Build output directory.svelte-kit/cloudflare

进一步阅读(Further reading)

¥Further reading

你可能希望参考 Cloudflare 关于在 Cloudflare Pages 上部署 SvelteKit 站点的文档

¥You may wish to refer to Cloudflare’s documentation for deploying a SvelteKit site on Cloudflare Pages.

注释(Notes)

¥Notes

项目根目录下的 /functions 目录 中包含的函数将不包含在部署中。相反,应该在你的 SvelteKit 应用中将函数实现为 服务器端点,该应用被编译为 单个 _worker.js 文件

¥Functions contained in the /functions directory at the project’s root will not be included in the deployment. Instead, functions should be implemented as server endpoints in your SvelteKit app, which is compiled to a single _worker.js file.

运行时 API(Runtime APIs)

¥Runtime APIs

env 对象包含你项目的 bindings,其中包括 KV/DO 命名空间等。它通过 platform 属性传递给 SvelteKit,以及 contextcachescf,这意味着你可以在钩子和端点中访问它:

¥The env object contains your project’s bindings, which consist of KV/DO namespaces, etc. It is passed to SvelteKit via the platform property, along with context, caches, and cf, meaning that you can access it in hooks and endpoints:

export async function 
function POST({ request, platform }: {
    request: any;
    platform: any;
}): Promise<void>
POST
({ request, platform }) {
const const x: anyx = platform: anyplatform.env.YOUR_DURABLE_OBJECT_NAMESPACE.idFromName('x'); }

对于环境变量,SvelteKit 的内置 $env 模块 应该是首选。

¥[!NOTE] SvelteKit’s built-in $env module should be preferred for environment variables.

要使这些类型可用于你的应用,请安装 @cloudflare/workers-types 并在你的 src/app.d.ts 中引用它们:

¥To make these types available to your app, install @cloudflare/workers-types and reference them in your src/app.d.ts:

src/app.d
import { interface KVNamespace<Key extends string = string>KVNamespace, interface DurableObjectNamespace<T extends Rpc.DurableObjectBranded | undefined = undefined>DurableObjectNamespace } from '@cloudflare/workers-types';

declare global {
	namespace App {
		interface interface App.Platform

If your adapter provides platform-specific context via event.platform, you can specify it here.

Platform
{
App.Platform.env?: {
    YOUR_KV_NAMESPACE: KVNamespace;
    YOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace;
} | undefined
env
?: {
type YOUR_KV_NAMESPACE: KVNamespace<string>YOUR_KV_NAMESPACE: interface KVNamespace<Key extends string = string>KVNamespace; type YOUR_DURABLE_OBJECT_NAMESPACE: DurableObjectNamespace<undefined>YOUR_DURABLE_OBJECT_NAMESPACE: interface DurableObjectNamespace<T extends Rpc.DurableObjectBranded | undefined = undefined>DurableObjectNamespace; }; } } } export {};

本地测试(Testing locally)

¥Testing locally

platform 属性中 Cloudflare 特定的值会在开发和预览模式下模拟。本地 bindings 是基于你的 Wrangler 配置文件 创建的,用于在开发和预览期间填充 platform.env。使用适配器配置 platformProxy 选项 更改绑定的首选项。

¥Cloudflare specific values in the platform property are emulated during dev and preview modes. Local bindings are created based on your Wrangler configuration file and are used to populate platform.env during development and preview. Use the adapter config platformProxy option to change your preferences for the bindings.

为了测试构建,你应该使用 Wrangler 版本 4。网站搭建完成后,如果你要测试 Cloudflare Workers,请运行 wrangler dev .svelte-kit/cloudflare;如果你要测试 Cloudflare Pages,请运行 wrangler pages dev .svelte-kit/cloudflare

¥For testing the build, you should use Wrangler version 4. Once you have built your site, run wrangler dev .svelte-kit/cloudflare if you’re testing for Cloudflare Workers or wrangler pages dev .svelte-kit/cloudflare for Cloudflare Pages.

标头和重定向(Headers and redirects)

¥Headers and redirects

Cloudflare 特有的 _headers_redirects 文件可用于静态资源响应(例如图片),只需将它们放入项目根文件夹即可。

¥The _headers and _redirects files, specific to Cloudflare, can be used for static asset responses (like images) by putting them into the project root folder.

但是,它们不会影响 SvelteKit 动态渲染的响应,SvelteKit 应该返回自定义标头或重定向来自 服务器端点 或使用 handle 钩子的响应。

¥However, they will have no effect on responses dynamically rendered by SvelteKit, which should return custom headers or redirect responses from server endpoints or with the handle hook.

故障排除(Troubleshooting)

¥Troubleshooting

Node.js 兼容性(Node.js compatibility)

¥Node.js compatibility

如果你想启用 Node.js 兼容性,你可以将 nodejs_compat 兼容性标志添加到你的 Wrangler 配置文件中:

¥If you would like to enable Node.js compatibility, you can add the nodejs_compat compatibility flag to your Wrangler configuration file:

wrangler
{
	"compatibility_flags": ["nodejs_compat"]
}

Worker 大小限制(Worker size limits)

¥Worker size limits

部署应用时,SvelteKit 生成的服务器将打包到单个文件中。如果在缩小后超过 大小限制,Wrangler 将无法发布你的工作程序。你通常不太可能达到此限制,但一些大型库可能会导致这种情况发生。在这种情况下,你可以尝试通过仅在客户端导入此类库来减小工作器的大小。有关更多信息,请参阅 常见问题解答

¥When deploying your application, the server generated by SvelteKit is bundled into a single file. Wrangler will fail to publish your worker if it exceeds the size limits after minification. You’re unlikely to hit this limit usually, but some large libraries can cause this to happen. In that case, you can try to reduce the size of your worker by only importing such libraries on the client side. See the FAQ for more information.

访问文件系统(Accessing the file system)

¥Accessing the file system

你不能在 Cloudflare Workers 中使用 fs — 你必须 prerender 相关路由。

¥You can’t use fs in Cloudflare Workers — you must prerender the routes in question.

从 Workers Sites 迁移(Migrating from Workers Sites)

¥Migrating from Workers Sites

Cloudflare 不再建议使用 Workers Sites,而是建议使用 Workers 静态资源。要迁移,请将 @sveltejs/adapter-cloudflare-workers 替换为 @sveltejs/adapter-cloudflare,并从 Wrangler 配置文件中删除所有 site 配置设置,然后添加 assets.directoryassets.binding 配置设置:

¥Cloudflare no longer recommends using Workers Sites and instead recommends using Workers Static Assets. To migrate, replace @sveltejs/adapter-cloudflare-workers with @sveltejs/adapter-cloudflare and remove all site configuration settings from your Wrangler configuration file, then add the assets.directory and assets.binding configuration settings:

svelte.config.js

svelte.config
import adapter from '@sveltejs/adapter-cloudflare-workers';
import import adapteradapter from '@sveltejs/adapter-cloudflare';

export default {
	
kit: {
    adapter: any;
}
kit
: {
adapter: anyadapter: import adapteradapter() } };

wrangler.toml

wrangler
site.bucket = ".cloudflare/public"
assets.directory = ".cloudflare/public"
assets.binding = "ASSETS"

wrangler.jsonc

wrangler
{
	"site": {
		"bucket": ".cloudflare/public"
	},
	"assets": {
		"directory": ".cloudflare/public",
		"binding": "ASSETS"
	}
}
上一页 下一页