部署到 Cloudflare Workers 或 Cloudflare Pages 时,使用 adapter-cloudflare。
使用 adapter-auto 时会默认安装这个适配器。如果计划持续使用 Cloudflare,可以直接改用它:本地开发会模拟 cloudflare:workers,自动应用类型声明,并允许设置 Cloudflare 专用选项。
适配器比较
adapter-cloudflare:支持所有 SvelteKit 功能,构建目标为 Workers Static Assets 与 Pages。adapter-cloudflare-workers:已弃用;支持所有 SvelteKit 功能,构建目标为 Workers Sites。adapter-static:只生成客户端静态资源,与 Workers Static Assets 和 Pages 兼容。
用法
运行 npx sv add sveltekit-adapter="adapter:cloudflare",或用 npm i -D @sveltejs/adapter-cloudflare 安装,然后在 vite.config.js 中添加适配器:
// @errors: 2307
/// file: vite.config.js
import adapter from '@sveltejs/adapter-cloudflare';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
sveltekit({
adapter: adapter({
// See below for an explanation of these options
config: undefined,
platformProxy: {
configPath: undefined,
environment: undefined,
persist: undefined
},
fallback: 'plaintext',
routes: {
include: ['/*'],
exclude: ['<all>']
}
})
})
]
});
选项
config
Wrangler 配置文件的路径。如果文件名不是 wrangler.jsonc、wrangler.json 或 wrangler.toml,可通过这个选项指定。
platformProxy
本地模拟 env 绑定的偏好设置。完整选项列表见 Wrangler 的 getPlatformProxy API。
fallback
决定对不匹配资源的请求生成纯文本 404.html,还是渲染 SPA 回退页面。
Workers 默认对不匹配资源的请求返回空响应体、404 状态。若 Wrangler 的 assets.not_found_handling 为 "404-page",请求未匹配资源时就会提供该页面。如果设置为 "single-page-application",适配器会生成 SPA 回退 index.html,而不受这里 fallback 选项的影响。
Pages 只有在请求匹配 routes.exclude 中某一项、却找不到对应资源时,才提供该页面。
通常 plaintext 已足够;如果手动用 routes.exclude 排除一些预渲染页面来避免超出 100 条路由限制,可以选择 spa,避免用户看到没有样式的 404 页面。详见 Pages 的未找到页面行为。
routes
仅用于 Pages,定制适配器生成的 _routes.json。
include:调用函数的路由,默认['/*']。exclude:不调用函数的路由,让静态资源的提供更快、更便宜。支持以下特殊值:<build>包含 Vite 构建产物;<files>包含static目录内容;<redirects>包含根目录_redirects中的路径;<prerendered>包含预渲染页面;默认<all>包含以上全部。
include 与 exclude 合计最多 100 条规则。通常可以省略 routes。如果预渲染路径超出限制,可手动用 '/articles/*' 替代自动生成的 ['/articles/foo', '/articles/bar', '/articles/baz', ...] 排除列表。
Cloudflare Workers
基础配置
构建 Workers 时,适配器要求项目根目录有 Wrangler 配置文件,形式如下:
/// file: wrangler.jsonc
{
"name": "<any-name-you-want>",
"main": ".svelte-kit/cloudflare/_worker.js",
"compatibility_flags": ["nodejs_als"],
"compatibility_date": "<YYYY-MM-DD>",
"assets": {
"binding": "ASSETS",
"directory": ".svelte-kit/cloudflare",
}
}
部署
运行 npx wrangler deploy,或用 Cloudflare Git 集成在推送时自动构建部署。
Cloudflare Pages
部署
从 Pages 的入门指南开始。使用 Git 集成时,构建设置如下:
- Framework preset:SvelteKit。
- Build command:
npm run build或vite build。 - Build output directory:
.svelte-kit/cloudflare。
配置后,在项目设置的 Runtime 部分添加 nodejs_als 兼容性标志,以启用 Node.js AsyncLocalStorage;也可在 Wrangler 配置的 compatibility_flags 数组中设置。
延伸阅读与注意事项
参阅 Cloudflare 关于在 Pages 上部署 SvelteKit 的文档。
项目根目录 /functions 中的函数不会包含在部署中。应改为实现 SvelteKit 的服务端端点,应用会编译为单个 _worker.js。
运行时 API
env 对象包含项目的绑定,如 KV/DO 命名空间。它来自 cloudflare:workers 模块:
import { env } from 'cloudflare:workers';
/** @type {import('./$types').RequestHandler} */
export async function POST() {
const x = env.YOUR_DURABLE_OBJECT_NAMESPACE.idFromName('x');
}
官方页面还提供 TypeScript 形式:
import { env } from 'cloudflare:workers';
import type { RequestHandler } from './$types';
export const POST: RequestHandler = async () => {
const x = env.YOUR_DURABLE_OBJECT_NAMESPACE.idFromName('x');
};
环境变量应优先使用 SvelteKit 内置的 $app/env/* 模块。安装 wrangler,运行 wrangler types 即可为应用提供这些类型。
本地测试
开发与预览模式会模拟 Cloudflare 专有值。根据 Wrangler 配置 创建本地绑定,并填入 env。用 platformProxy 选项调整绑定偏好。
需要从 Worker 导出自定义类的 Durable Objects 与 Workflows 当前不受支持。
测试构建产物时使用 Wrangler 4。构建完成后,Workers 使用 wrangler dev .svelte-kit/cloudflare/_worker.js,Pages 使用 wrangler pages dev .svelte-kit/cloudflare。
响应头与重定向
将 Cloudflare 专用的 _headers 与 _redirects 放在项目根目录,可以作用于图片等静态资源的响应。
它们对 SvelteKit 动态渲染响应没有效果。动态响应应通过服务端端点或 handle 钩子设置自定义响应头或重定向。
故障排查
Node.js 兼容性
如需启用 Node.js 兼容性,为 Wrangler 添加:
/// file: wrangler.jsonc
{
"compatibility_flags": ["nodejs_compat"]
}
Worker 大小限制
部署时,SvelteKit 生成的服务端程序会打包为单个文件。如果压缩后的 Worker 超出大小限制,Wrangler 会拒绝发布。通常不会遇到,但大型库可能导致超限。可尝试只在客户端导入这些库,见常见问题。
访问文件系统
Workers 中不能使用 fs。改用 $app/server 的 read 函数;它会从已部署的公开资源位置获取文件。也可预渲染对应路由。
从 Workers Sites 迁移
Cloudflare 不再推荐 Workers Sites,建议使用 Workers Static Assets。将 @sveltejs/adapter-cloudflare-workers 替换为 @sveltejs/adapter-cloudflare,移除 Wrangler 的全部 site 设置,加入 assets.directory 和 assets.binding。
以下保留原文的差异标记:--- 表示删除,+++ 表示添加;它们不是可直接运行的配置语法。
vite.config.js:
// @errors: 2307
/// file: vite.config.js
+++import adapter from '@sveltejs/adapter-cloudflare';+++
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
sveltekit({
+++adapter: adapter()+++
})
]
});
wrangler.toml:
/// file: wrangler.toml
---site.bucket = ".cloudflare/public"---
+++assets.directory = ".cloudflare/public"
assets.binding = "ASSETS" # Exclude this if you don't have a `main` key configured.+++
wrangler.jsonc:
/// file: wrangler.jsonc
{
--- "site": {
"bucket": ".cloudflare/public"
},---
+++ "assets": {
"directory": ".cloudflare/public",
"binding": "ASSETS" // Exclude this if you don't have a `main` key configured.
}+++
}
原文:SvelteKit 文档:Cloudflare。作者:SvelteKit 文档贡献者。本版本翻译正文并调整版式;示例以当前官方页面及对应仓库原文为依据。采用 MIT 许可。
Copyright (c) 2020 SvelteKit contributors (https://github.com/sveltejs/kit/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.











暂无评论内容