跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

开发、构建和部署

最后更新 查看 MarkdownAgent 设置

cf 使用管理 Cloudflare 账户其余部分的同一 CLI 来开发、构建和部署 Workers 项目。要创建项目,请遵循部署你的第一个 Worker。

使用 cloudflare.config.ts 配置项目。构建将 Build Output 写入 .cloudflare/output/v0/。

cf 如何运行项目

cf 本身不会运行开发服务器或打包器。对于 cf dev、cf build 以及所有会先构建的其他命令,cf 将工作交给以下工具之一:

  1. 框架自身的命令。 当 cf 检测到受支持的框架时,它通过你的包管理器运行该框架的 dev 或 build 命令。在 Vite 项目(包括用 cf init 创建的项目)中,这是 vite 或 vite build,例如使用 npm 时为 npx vite build。
  2. 已安装的 Cloudflare 构建工具。 否则,cf 使用项目 package.json 中声明的 Cloudflare 构建工具。即 Cloudflare Vite 插件;未声明 Vite 插件时,则为 Wrangler 4.136.0 或更高版本。

cf 使用 Cloudflare Vite 插件 2.0 Beta(@cloudflare/vite-plugin@beta),它不依赖 Wrangler。声明了 Wrangler 但未声明 Vite 插件的项目由 Wrangler 构建,例如 cf migrate 用 Wrangler 打包器转换的项目,以及自动配置设置的静态站点。这些项目将静态资源目录等构建设置保存在生成的 wrangler.config.ts 文件中。该文件在 Beta 期间可能变化。

cf 不会运行你的 package.json 脚本。如果你的 build 脚本运行额外步骤(例如 tsc -b && vite build),则 cf build 和 cf deploy 会跳过它们。请改为在自己的脚本中将这些步骤与 cf build 串联:

package.jsonjson
{
    "scripts": {
        "build": "tsc -b && cf build"
    }
}

当 cf 运行框架命令时,它会转发 --mode 并拒绝其他参数。例如,cf dev --port 8788 在 Vite 项目中会失败。请在框架配置中设置该选项(例如 vite.config.ts 中的 server.port),或直接运行框架命令。当 cf 改为使用已安装的构建工具时,cf dev 会将额外参数转发给它,工具会拒绝它不支持的参数。cf build 只接受 --mode。

自动配置

当项目没有 cloudflare.config.ts 时,cf 会尝试检测其框架,并在继续之前为 Cloudflare 设置项目。自动配置由这些命令运行:

  • cf dev 和 cf build
  • cf deploy,包括 cf deploy --dry-run
  • cf previews deploy
  • cf workers versions create、cf workers triggers deploy 和 cf workers check
  • cf init

仅当运行命令的目录中存在 cloudflare.config.ts 时,项目才算已配置。传入 --prebuilt 会跳过自动配置。

在终端中,cf 会显示计划的更改,并在应用之前询问。没有终端或在 CI 中时,它会在不问询的情况下应用更改并安装软件包。在设置 CI 之前,请先在本地运行 cf init .。它会配置现有项目而不构建。审查更改并提交。更改列表请参阅从现有项目开始。

开始开发

启动项目的开发服务器:

cf dev

开发服务器会输出其本地 URL。将 /cdn-cgi/local/explorer 附加到该 URL 以打开 Local Explorer。你可以使用它检查本地绑定(binding)数据、查看日志和 trace,并使用选定的 cron 表达式和计划时间测试 Cron Trigger。

构建

构建项目:

cf build

构建完成后,cf 会读取并验证 .cloudflare/output/v0/。cf build 不会上传任何内容,也不需要凭据。

部署

cf deploy 会构建项目、验证 Build Output、解析凭据和账户、上传新的 Worker Version,并部署它:

cf deploy

部署前请使用 cf auth login 登录,或设置 CLOUDFLARE_API_TOKEN。详情请参阅登录。

cf deploy 可以为省略资源标识符的绑定预配缺失资源。它不会将已预配的标识符写回 cloudflare.config.ts。

cf deploy 接受这些选项:

选项 用途
--dry-run 构建并验证 Worker,而不上传
--message <TEXT> 在 Worker Version 上记录消息
--tag <TAG> 在 Worker Version 上记录标签
--secrets-file <PATH> 随该版本从 JSON 或 .env 格式文件上传 secrets
--dispatch-namespace <NAMESPACE> 将 Workers for Platforms 用户 Worker 部署到该 dispatch namespace
--containers-rollout <STRATEGY> 设置 Container 发布策略:immediate、gradual 或 none
--worker <NAME> 从 Build Output 选择 Worker,而不是默认 Worker
--prebuilt 部署现有 Build Output,而不构建

--dry-run 不发送 API 请求,也不需要凭据,因此你可以在登录前验证项目。在没有 cloudflare.config.ts 的项目中,它仍会先运行自动配置,这可能会安装软件包并更改文件。

cf deploy --dry-run
cf deploy --message "Fix header parsing" --tag v1.2.0

模式

模式选择函数形式的 cloudflare.config.ts 返回哪份配置。用 --mode 或 -m 传入:

cf dev --mode staging
cf build -m staging
cf deploy --mode staging

省略 --mode 时,Cloudflare Vite 插件对 cf dev 使用 development,对构建使用 production。通过 Wrangler 的构建和 API 命令会将模式保留为 undefined。完整列表请参阅选择模式。

当 cf 运行框架自身的命令时,只有 Vite 和 Astro 接受 --mode。其他框架命令会失败并报错。请参阅框架拒绝 --mode。

此配置会部署带有独立 API origin 的单独 staging Worker:

Select a highlighted line to show its type and description below it.

cloudflare.config.ts
import { bindings, defineConfig } from "cf/config";
import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };
export default defineConfig(({ mode }) => { (defineConfig, mode reference)

defineConfigFunctionLink to defineConfig

defineConfig<T extends ConfigInput<CloudflareConfig>>(config: T): T;

Defines the default export of cloudflare.config.ts. Pass a configuration object, a promise that resolves to one, or a function that receives the config context (isPreview and mode) and returns either.

Options (4)
accountId?: string
This is the ID of the account associated with your zone. It can also be specified through the CLOUDFLARE_ACCOUNT_ID environment variable.
complianceRegion?: "public" | "fedramp-high"
The compliance boundary in which commands should operate. When omitted, this can be supplied through CLOUDFLARE_COMPLIANCE_REGION.
worker?: ConfigInput<WorkerConfig>
The Worker defined by this configuration.
containers?: ConfigInput<ContainerConfig>[]
Container applications defined by this configuration.

modeContext valueLink to mode

mode: string | undefined

The mode the config is being evaluated in. Set via the --mode CLI flag. In Vite the mode defaults to development in vite dev and production in vite build (more info). In Wrangler the mode defaults to undefined.

const isStaging = mode === "staging";
return {
worker: { (worker reference)

workerOptionalLink to worker

worker?: ConfigInput<WorkerConfig>

The Worker defined by this configuration.

name: isStaging ? "example-worker-staging" : "example-worker", (name reference)

nameRequiredLink to name

name: string

The name of your Worker.

entrypoint, (entrypoint reference)

entrypointOptionalLink to entrypoint

entrypoint?: string | WorkerModule

The entrypoint module that will be executed. May be either a path string (e.g. "./src/index.ts") or a module namespace imported with the cf-worker import attribute.

compatibilityDate: "<COMPATIBILITY_DATE>", (compatibilityDate reference)

compatibilityDateRequiredLink to compatibilityDate

compatibilityDate: string

A date in the form yyyy-mm-dd, which will be used to determine which version of the Workers runtime is used. More details at https://developers.cloudflare.com/workers/configuration/compatibility-dates

env: { (env reference)

envOptionalLink to env

env?: Record<string, Binding>

Bindings exposed on the Worker's env object. Construct entries with bindings.kv(...), bindings.r2(...), etc.

API_ORIGIN: bindings.text( (text reference)

textBuilderLink to text

text<T$1 extends string>(value: T$1): TextBinding<T$1>;

Inline string value made available to the Worker on env under the binding name. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables

isStaging
? "https://staging-api.example.com"
: "https://api.example.com",
),
},
},
};
});

为每个模式返回一份完整配置。编程式配置不会像 Wrangler 环境那样合并环境块。仅当模式返回不同的 name 时,才会部署单独的 Worker。

Build Output 会记录构建时所使用的模式。部署现有构建时,请传入相同模式。

部署预构建输出

传入 --prebuilt 可部署现有的 .cloudflare/output/v0/ 目录,而不构建。一个 CI 作业可以构建,另一个作业可以部署已还原的目录。--prebuilt 也会跳过自动配置。

部署命令必须请求 Build Output 所记录的模式:

  • 当 Build Output 记录了模式时,用 --mode 精确传入该模式。
  • 当 Build Output 未记录模式时,不要传入 --mode。

Vite 构建始终记录模式。不带 --mode 的 cf build 会记录 production,因此用 --mode production 部署该构建:

cf build
cf deploy --prebuilt --mode production

用 staging 模式部署 staging 构建:

cf build --mode staging
cf deploy --prebuilt --mode staging

通过 Wrangler 的构建仅在你向 cf build 传入 --mode 时记录模式。要查看所记录的模式,请读取 .cloudflare/output/v0/config.json 中的 buildContext.mode。

相同规则适用于带 --prebuilt 的 cf previews deploy、cf workers versions create、cf workers triggers deploy 和 cf workers check。模式不匹配时,命令会在上传任何内容之前停止,并打印应使用的 --mode 值。

完整流水线请参阅在 CI 中使用 cf。

上传版本

上传 Worker Version 而不部署它:

cf workers versions create

此命令以与 cf deploy 相同的方式构建并验证项目。它接受 --prebuilt、--mode、--message、--tag、--secrets-file、--dry-run 和 --worker。使用 --preview-alias <ALIAS> 可为该版本指定 preview URL 别名。

要将流量发送到已上传的版本,请创建部署:

cf workers deployments create --worker example-worker --strategy percentage --versions '[{"version_id":"<VERSION_ID>","percentage":100}]'

部署触发器

从 Build Output 应用触发器配置,而不上传新版本:

cf workers triggers deploy

此命令应用路由、自定义域名、workers.dev 设置、cron 计划、Queue consumers 和 Workflows。除非传入 --prebuilt,否则它会构建项目。它还接受 --mode、--worker 和 --dry-run。Dry run 不发送 API 请求。

部署预览

将项目部署为 Worker Preview:

cf previews deploy

该命令以 isPreview 设为 true 构建项目,因此函数形式的 cloudflare.config.ts 可以返回预览专用设置。然后它上传预览,并以 JSON 打印结果。cf 中的预览在 Beta 期间可能变化。

预览名称默认为当前分支。cf 从 Workers Builds、GitHub Actions 或 GitLab CI/CD 读取分支,然后从 Git 读取。在没有 CI 分支的游离 HEAD 上,请传入名称:

cf previews deploy my-feature

该命令接受 --mode、--worker 和 --prebuilt。使用 --prebuilt 时,Build Output 必须来自预览构建,并且适用模式规则。没有 --dry-run,且命令需要凭据。

JSON 结果包含 type、version、preview_id、preview_name、preview_slug、preview_urls、deployment_id 和 deployment_urls。

预览不支持 Durable Object 管理的 Containers。cf deploy、cf workers versions create 和 cf workers triggers deploy 会拒绝预览 Build Output,并打印应改用的 cf previews deploy 命令。

分析 Worker 启动性能

在本地分析 Worker 的启动性能:

cf workers check

除非传入 --prebuilt,否则该命令会构建项目。它以 JSON 打印包大小和启动耗时,并将 CPU profile 写入 worker-startup.cpuprofile。使用 --outfile <PATH> 可选择其他文件。该命令还接受 --mode 和 --worker。

测量在你的机器上运行。用它查找启动时间花在哪里,而不是预测 Cloudflare 上的启动时间。

生成类型

从 cloudflare.config.ts 生成 TypeScript 类型:

cf workers types

该命令写入 .cloudflare/types/index.d.ts,其中包含 Env 绑定类型和 Workers 运行时类型。传入 --no-include-runtime 可省略运行时类型,或传入 --mode 以为命名模式求值配置。

Cloudflare Vite 插件在开发和构建期间写入同一文件。在通过 Wrangler 构建的项目中,或在类型检查脚本中于 tsc 之前运行 cf workers types。通过 cf init 创建的项目包含运行 cf workers types && tsc 的 typecheck 脚本。

本地资源数据

向受支持的命令添加 --local,使其针对本地模拟运行,而不是 Cloudflare API:

cf d1 raw <DATABASE_ID> --sql "SELECT 1" --local
cf r2 objects list --bucket-name <BUCKET_NAME> --local

--local 仅适用于本地开发提供的少数资源。cf 为每条命令启动短生命周期的本地运行时,因此无需正在运行的开发服务器。本地支持覆盖这些命令:

  • cf kv keys get、cf kv keys list、cf kv keys put 和 cf kv keys delete
  • cf kv bulk get、cf kv bulk put 和 cf kv bulk delete
  • cf d1 raw
  • cf d1 migrations list 和 cf d1 migrations apply
  • cf r2 objects get、cf r2 objects put、cf r2 objects list 和 cf r2 objects bulk-delete
  • cf flagship apps flags list、get、create、update、patch、delete 和 evaluate
  • cf flagship apps evaluate get
  • cf d1 list、cf kv namespaces list、cf flagship apps list 和 cf r2 buckets list

cf d1 query 没有本地等效项。请改用 cf d1 raw。没有本地等效项的命令会失败,并显示 This command has no local equivalent.,而不是调用 Cloudflare API。

默认情况下,--local 将其数据保存在 cf 配置目录内的 state/v3 目录中。在 Linux 上为 ~/.config/cloudflare/state/v3,在 macOS 上为 ~/Library/Preferences/cloudflare/state/v3。本机上的每个项目共享此目录。传入 --persist-to <DIRECTORY> 可改用 <DIRECTORY>/v3。--persist-to 仅与 --local 一起使用。

这不是开发服务器使用的数据。Cloudflare Vite 插件 2.0 Beta 将开发数据保存在项目中的 .cloudflare/state/。

每条命令读取哪份配置

项目命令(例如 cf dev、cf build 和 cf deploy)会运行构建工具,加载整个 cloudflare.config.ts,包括 Worker 和 Containers。

普通 API 命令(例如 cf d1 list)仅从当前目录或父目录中最近的 cloudflare.config.ts 读取 accountId 和 complianceRegion。该文件中的语法错误、导入错误或顶层运行时错误仍会阻止它们。详情请参阅设置账户默认值。

CLOUDFLARE_API_TOKEN 等 API 凭据也可以来自当前目录的 .env 文件。会先构建的命令(例如 cf deploy)在构建完成后加载这些值。详情请参阅从 .env 文件加载凭据。

故障排除

未安装开发服务器

No Cloudflare dev-server is installed in this project.

cf 未找到它识别的框架,也未在 package.json 中声明 Cloudflare 构建工具,例如空目录。要创建项目,请运行 cf init。

未安装依赖

在已配置但未安装依赖的项目中,Vite 会报告无法解析 @cloudflare/vite-plugin,或 cf 会报告已声明构建工具但未安装。请用包管理器安装依赖,然后再次运行命令。

参数被拒绝

Arguments cannot currently be forwarded to the detected dev command `npx vite`. Run that command directly with the required arguments.

cf 运行框架命令,并且只转发 --mode。请在框架配置中设置该选项,或直接运行框架命令。

框架拒绝 --mode

The detected command `<COMMAND>` does not currently support `--mode`.

当 cf 运行框架命令时,只有 Vite 和 Astro 接受 --mode。请不带 --mode 运行命令。

预构建部署拒绝该模式

The Build Output was created with mode "production", but this command did not specify a mode. Rerun with "--mode production".
The Build Output does not record which mode it was created with, but this command requested mode "staging". Rebuild with "--mode staging" before deploying.

请精确传入 Build Output 所记录的模式;未记录时省略 --mode。请参阅部署预构建输出。

缺少 Build Output

Build Output Specification: no root config found at <PATH>/.cloudflare/output/v0/config.json.

--prebuilt 命令未找到构建。请先运行 cf build,或从构建作业还原完整的 .cloudflare/output/v0/ 目录。

预览输出到达生产部署

This build output is for a Preview. Run cf previews deploy --prebuilt --mode production instead.

现有 Build Output 来自 cf previews deploy。运行建议的命令以部署预览,或运行 cf build 以创建生产输出。

无法确定预览名称

We couldn't determine a Preview name from CI or Git.

cf previews deploy 未找到分支名称,例如在游离 HEAD 上。请传入名称:cf previews deploy <PREVIEW_NAME>。

本地命令没有本地等效项

This command has no local equivalent. Re-run without --local to use the Cloudflare API.

该命令不支持 --local。对于 D1 查询,请使用 cf d1 raw 而不是 cf d1 query。否则,不带 --local 运行命令。

这篇文档对您有帮助吗?