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

部署你的第一个 Worker

最后更新 查看 MarkdownAgent 设置

本指南使用 cf init 创建 Worker,在本机运行,并将其部署到你的 Cloudflare 账户。

开始之前

安装 cf 并查看要求。直到部署时才需要登录。

1. 创建项目

在新目录中创建项目:

cf init my-worker

cf init 会询问使用哪个包管理器,在 my-worker 中创建项目,安装依赖,并为绑定生成类型。如果省略目录,cf init 会询问一个目录。

除了 node_modules 和安装产生的 lockfile 之外,cf init 会创建这些文件:

  • my-worker/
    • .cloudflare/
      • types/
        • index.d.ts
    • src/
      • index.ts
    • .gitignore
    • cloudflare.config.ts
    • package.json
    • tsconfig.json
    • vite.config.ts
  • src/index.ts 是 Worker。
  • cloudflare.config.ts 用 TypeScript 描述 Worker。
  • vite.config.ts 添加 Cloudflare Vite 插件,在开发期间于 Workers 运行时中运行代码,并为部署进行构建。
  • package.json 包含运行对应 cf 命令的 dev、build 和 deploy 脚本。它列出 cf 以及 cf 使用的 Vite 插件 2.0 Beta(@cloudflare/vite-plugin@beta),但不包含 Wrangler。
  • .cloudflare/types/index.d.ts 保存生成的绑定和运行时类型。运行 cf dev 或 cf build 时,Vite 插件会更新它。生成的 .gitignore 会排除 .cloudflare/。

Worker 读取 WORLD 绑定并返回问候语:

src/index.jsjs
import { env } from "cloudflare:workers";

export default {
	fetch() {
		return new Response(`Hello ${env.WORLD}!`);
	},
};
src/index.tsts
import { env } from "cloudflare:workers";

export default {
	fetch() {
		return new Response(`Hello ${env.WORLD}!`);
	},
} satisfies ExportedHandler;

cloudflare.config.ts 为 Worker 命名、指向其入口,并声明 WORLD 文本绑定。注释说明每个字段和构建器:

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({ (defineConfig 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.
worker: { (worker reference)

workerOptionalLink to worker

worker?: ConfigInput<WorkerConfig>

The Worker defined by this configuration.

name: "my-worker", (name reference)

nameRequiredLink to name

name: string

The name of your Worker.

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

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.

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.

WORLD: bindings.text("World"), (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

},
},
});

cf init 将 compatibilityDate 设为随你的 cf 版本一起提供的固定近期日期。cf-worker 导入属性将配置指向你的 Worker 模块。cf 从中读取模块路径,不会加载或运行你的 Worker 代码。

2. 本地开发

启动开发服务器:

cd my-worker
cf dev

打开 cf dev 打印的本地 URL,默认是 http://localhost:5173/。Worker 会响应 Hello World!。

在 src/index.ts 中更改响应,保存文件,然后刷新页面。开发服务器会在无需重启的情况下拾取更改。

在此项目中,cf dev 不接受 --port 等选项。要更改端口,请在 vite.config.ts 中设置 server.port。

3. 部署

  1. 如果尚未登录,请登录:

    cf auth login
  2. 部署 Worker:

    cf deploy

    cf deploy 会构建项目、上传 Worker、将其部署到你的账户,并打印结果。如果你可以访问多个账户,cf 会询问使用哪一个。要了解如何设置默认账户,请参阅选择账户。

要在不部署的情况下检查构建,请运行 cf deploy --dry-run。Dry run 不会发出 API 请求,因此可以在登录之前使用。

在无提示的情况下创建项目

在脚本或 CI 作业中,cf init 无法提问,因此请传入目录。用 --package-manager 选择包管理器,它接受 npm、pnpm、yarn 或 bun。未指定时,cf init 使用 npm,除非你通过其他包管理器运行了 cf:

cf init my-worker --package-manager npm

要跳过安装,请添加 --no-install。然后在运行 cf dev 之前,在项目中运行包管理器的安装命令。

从现有项目开始

cf 也可以设置现有应用。在项目目录中安装依赖,然后运行 cf init .:

cf init .

cf 会检测框架并显示它找到的设置,包括 Worker 名称、框架、构建命令和输出目录。你确认后,cf 会更改项目。对于 Vite 应用,它会:

  • 将 cf 和 @cloudflare/vite-plugin 安装为开发依赖。
  • 将 Cloudflare 插件添加到 vite.config.ts,或创建该文件。
  • 创建 cloudflare.config.ts,并开启可观测性。
  • 添加运行 cf deploy 的 deploy 脚本。
  • 向 .gitignore 添加 .wrangler、.dev.vars* 和 .env* 条目。在没有 .gitignore 文件的 Git 仓库中,它会创建一个。

cf 不会把写入构建和生成类型的 .cloudflare/ 加入 .gitignore。请自行添加:

echo ".cloudflare/" >> .gitignore

cf build 和 cf deploy 运行框架自身的构建命令(例如 vite build),而不是 package.json 中的 build 脚本。要保留额外的构建步骤,请参阅 cf 如何运行项目。

如果跳过 cf init .,则 cf dev、cf build 和 cf deploy 会在你首次使用它们时运行相同的设置。在 CI 中,它们会在不问询的情况下应用更改,因此请先在本地运行 cf init . 并提交结果。详情请参阅自动配置。

纯 Vite 应用适用于此流程。cf 也会检测其他框架,例如 Astro、React Router 和 SvelteKit,但检测并不意味着项目能够构建。例如,Astro 6 及更高版本在 Beta 期间无法通过 cf 构建。

后续步骤

这篇文档对您有帮助吗?