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

编程式配置

最后更新 查看 MarkdownAgent 设置

cloudflare.config.ts 是 Workers 项目中带类型的配置文件。 其默认导出可以定义 Worker、Container 应用和账户设置。 由于此文件是 TypeScript 模块,它可以使用导入、函数、环境变量和异步值。

加载 cloudflare.config.ts 需要 Node.js 22.18 或更高版本。不支持 Bun:当 cf 在 Bun 上运行时,加载此文件会失败,并显示 cloudflare.config.ts loading is not supported on Bun。大多数 cf 命令都会加载最近的 cloudflare.config.ts,包括仅调用 Cloudflare API 的命令,因此这是在项目中运行任何 cf 命令的实际最低版本要求。

在项目的 package.json 中设置 "type": "module"。否则,Node.js 每次加载文件时都会显示警告。如果设置为 "type": "commonjs",加载会失败,并显示 Cannot use import statement outside a module。

创建最小配置

从 cf/config 导入配置辅助函数。将 cf 添加为开发依赖,以便项目能够解析该导入。通过 cf init 创建的项目已经包含此依赖。

npm i -D cf

Worker 需要 name 和 compatibilityDate。运行代码的 Worker 还需要 entrypoint。

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

cloudflare.config.ts
import { 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: "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

},
});

cf-worker 导入属性使 TypeScript 能够推断 Worker 模块、绑定类型和导出的类。

仅提供资源的 Worker 可以省略 entrypoint。其构建实现必须提供资源来源。可部署的构建必须包含 Worker 包、静态资源或两者。

cloudflare.config.ts 没有 assets.directory 字段。在 Vite 项目中,静态资源来自 Vite 客户端构建的输出,其中包含 Vite 的 publicDir 目录(默认为 public)。使用 Wrangler 构建的项目会在生成的 wrangler.config.ts 文件中设置目录。详情请参阅 cf 如何运行项目。

了解默认导出

使用 defineConfig() 作为默认导出。此辅助函数返回传入的值,并保留字面量值以供 TypeScript 推断。

字段 是否必需 用途
accountId 否 为 cf 命令设置默认账户
complianceRegion 否 选择 public 或 fedramp-high
worker 开发和构建时必需 定义 Worker
containers 否 定义 Container 应用

cf API 命令可以读取仅包含账户设置的默认导出。Cloudflare Vite 插件和 Wrangler 在开发和构建时需要 worker。

使用配置浏览器查看生成的字段、构建器方法和嵌套选项。

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

cloudflare.config.ts
import { bindings, defineConfig, triggers } 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 {
accountId: "<ACCOUNT_ID>", (accountId reference)

accountIdOptionalLink to accountId

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", (complianceRegion reference)

complianceRegionOptionalLink to complianceRegion

complianceRegion?: "public" | "fedramp-high"

The compliance boundary in which commands should operate. When omitted, this can be supplied through CLOUDFLARE_COMPLIANCE_REGION.

worker: { (worker reference)

workerOptionalLink to worker

worker?: ConfigInput<WorkerConfig>

The Worker defined by this configuration.

name: isStaging ? "example-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.

MESSAGE: bindings.text(isStaging ? "staging" : "production"), (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

},
triggers: [triggers.scheduled({ schedule: "0 * * * *" })], (triggers, scheduled, schedule reference)

triggersOptionalLink to triggers

triggers?: Trigger[]

Event triggers — fetch routes, queue consumers, cron schedules, Email Routing addresses, and raw sockets — that invoke this Worker. Construct entries with triggers.fetch(...), triggers.queue(...), triggers.scheduled(...), triggers.email(...), or triggers.connect(...). For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers

scheduledBuilderLink to scheduled

scheduled(options: ScheduledTriggerOptions): ScheduledTrigger;

Scheduled (cron) trigger — invokes this Worker on the given schedules. More details here https://developers.cloudflare.com/workers/platform/cron-triggers

Options (1)
schedule: string
A "cron" definition to trigger a Worker's "scheduled" function. Lets you call Workers periodically, much like a cron job. More details here https://developers.cloudflare.com/workers/platform/cron-triggers

scheduleRequiredLink to schedule

schedule: string

A "cron" definition to trigger a Worker's "scheduled" function. Lets you call Workers periodically, much like a cron job. More details here https://developers.cloudflare.com/workers/platform/cron-triggers

},
};
});

求值配置

defineConfig()、defineWorker() 和 defineContainer() 都接受对象、promise 或函数。函数可以返回对象或 promise。

函数接收以下上下文:

属性 用途
mode 标识所选模式;省略 --mode 时,模式取决于命令
isPreview 为 Worker Preview 求值配置时为 true

为每个模式返回一个完整配置。编程式配置不会合并环境块。

复用定义

当其他配置文件需要导入 Worker 定义时,使用 defineWorker()。当 Durable Object 导出和 containers 数组需要引用同一个 Container 时,使用 defineContainer()。

这些辅助函数不会替代默认导出。默认导出仍必须使用 defineConfig()。

配置 Worker

worker 对象支持以下字段:

字段 是否必需 用途
name 是 设置 Worker 名称
compatibilityDate 是 选择 Workers 运行时兼容性日期
entrypoint 条件兼容 选择 Worker 模块
assets 否 设置已构建资源的运行时请求行为
cache 否 配置 Worker 缓存行为
compatibilityFlags 否 开启运行时兼容性标志
domains 否 将 Worker 发布到自定义域名
env 否 声明绑定和内联值
exports 否 配置命名的 Worker、Durable Object 和 Workflow 导出
limits 否 设置 CPU 和子请求限制
logpush 否 将跟踪事件发送到 Workers Logpush
observability 否 配置日志、跟踪和采样
placement 否 配置智能或定向放置
previewUrls 否 控制版本预览 URL
tailConsumers 否 将事件发送到 Tail Workers
triggers 否 声明路由、队列、计划和套接字
unsafe 否 将不受支持的元数据传递到部署
workersDev 否 控制 workers.dev 路由

assets 对象仅控制运行时行为。它配置 HTML 处理、未找到资源时的处理,以及匹配请求是否优先运行 Worker。它不会选择资源来源。

自定义域名使用 domains,路由使用 triggers.fetch()。

使用带类型的构建器值

bindings、triggers 和 exports 构建器返回普通配置对象。每个对象都有标识其种类的字面量 type 字段。

type 字段使 TypeScript 能够为每种类型选择有效选项。例如,队列触发器接受批处理选项,而计划触发器需要 cron 表达式。配置加载器使用相同字段进行运行时验证。

使用构建器,无需直接编写 type 字段。构建器会保留字面量值和泛型类型参数,以供 Worker 类型推断。

声明绑定

worker.env 下的每个键都会成为 Worker 代码中的绑定名称。构建器方法决定绑定的运行时类型。

此配置声明内联值、D1 数据库、Queue 和秘密:

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" };
type Job = {
id: string;
operation: "index" | "delete";
};
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: "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("https://api.example.com"), (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

FEATURES: bindings.json({ search: true }), (json reference)

jsonBuilderLink to json

json<T$1 extends Json>(value: T$1): JsonBinding<T$1>;

Inline JSON value made available to the Worker on env under the binding name.

DATABASE: bindings.d1({ name: "application-db" }), (d1, name reference)

d1BuilderLink to d1

d1(options?: D1BindingOptions): D1Binding;

Binding to a D1 database. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#d1-databases

Options (3)
id?: string
The UUID of this D1 database (not required).
name?: string
The name of this D1 database.
dev?: BindingDevOptions
Options that only apply during local development.

nameOptionalLink to name

name?: string

The name of this D1 database.

JOBS: bindings.queue<Job>({ name: "application-jobs" }), (queue, name reference)

queueBuilderLink to queue

queue<TBody = unknown>(options?: QueueBindingOptions): TypedQueueBinding<TBody>;

Producer binding to a Cloudflare Queue. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#queues

Options (3)
name?: string
The name of this Queue.
deliveryDelay?: number
The number of seconds to wait before delivering a message.
dev?: BindingDevOptions
Options that only apply during local development.

nameOptionalLink to name

name?: string

The name of this Queue.

API_KEY: bindings.secret(), (secret reference)

secretBuilderLink to secret

secret(): SecretBinding;

Declares a secret that is required by your Worker, exposed on env under the binding name. When defined, this binding: - Replaces .dev.vars/.env/process.env inference for type generation - Enables local dev validation with warnings for missing secrets For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#secrets-configuration-property

},
},
});

生成的 Env 类型包含以下运行时类型:

绑定 推断的运行时类型
API_ORIGIN "https://api.example.com"
FEATURES { search: true }
DATABASE D1Database
JOBS Queue<Job>
API_KEY string

Worker 通过 env 接收推断的类型:

src/index.jsjs
export default {
	async fetch(_request, env) {
		await env.JOBS.send({
			id: "example-job",
			operation: "index",
		});

		const result = await env.DATABASE.prepare("SELECT 1").first();
		return Response.json({
			origin: env.API_ORIGIN,
			search: env.FEATURES.search,
			result,
		});
	},
};
src/index.tsts
export default {
    async fetch(_request, env) {
        await env.JOBS.send({
            id: "example-job",
            operation: "index",
        });

        const result = await env.DATABASE.prepare("SELECT 1").first();
        return Response.json({
            origin: env.API_ORIGIN,
            search: env.FEATURES.search,
            result,
        });
    },
} satisfies ExportedHandler<Env>;

Cloudflare Vite 插件会在开发和构建期间写入 .cloudflare/types/index.d.ts。在 Vite 工作流程之外,cf workers types 会写入同一文件。

TypeScript 通配符模式会跳过以点开头的目录,因此需要显式包含生成的目录。本页示例中的 .ts 扩展名还需要 allowImportingTsExtensions:

tsconfig.jsonjson
{
    "compilerOptions": {
        "allowImportingTsExtensions": true,
        "noEmit": true
    },
    "include": ["src", "cloudflare.config.ts", ".cloudflare/types"]
}

构建器 API 包含以下方法:

领域 构建器方法
内联值 text, json, secret
存储与数据 d1, kv, r2, hyperdrive, analyticsEngineDataset, artifacts, pipeline
AI 与媒体 ai, aiSearch, aiSearchNamespace, agentMemory, browser, images, media, stream, vectorize
消息传递 queue, sendEmail
Worker 组合 assets, dispatchNamespace, durableObject, worker, workerLoader, workflow
网络与安全 mtlsCertificate, rateLimit, secretsStoreSecret, vpcNetwork, vpcService
平台元数据 flagship, logfwdr, versionMetadata

必需选项因绑定而异。TypeScript 自动补全会显示每个构建器的选项。

为跨 Worker 绑定定义类型

bindings.worker()、bindings.durableObject() 和 bindings.workflow() 接受 Worker 名称或 Worker 定义。导入 Worker 定义可在编译时验证其导出名称。

例如,API Worker 可以导出其定义:

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

api/cloudflare.config.ts
import { defineConfig, defineWorker, exports } from "cf/config";
import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };
export const apiWorker = defineWorker({ (defineWorker reference)

defineWorkerFunctionLink to defineWorker

defineWorker<T extends ConfigInput<WorkerConfig>>(config: T): T;

Defines a Worker configuration that you can pass to worker in defineConfig(). Pass a Worker configuration object, a promise that resolves to one, or a function that receives the config context (isPreview and mode) and returns either.

Options (18)
name: string
The name of your Worker.
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
compatibilityFlags?: string[]
A list of flags that enable features from upcoming features of the Workers runtime, usually used together with compatibilityDate. More details at https://developers.cloudflare.com/workers/configuration/compatibility-flags/
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.
assets?: { /** How to handle HTML requests. */ htmlHandling?: "auto-trailing-slash" | "drop-trailing-slash" | "force-trailing-slash" | "none"; /** How to handle requests that do not match an asset. */ notFoundHandling?: "single-page-application" | "404-page" | "none"; /** * Matches will be routed to the User Worker, and matches to negative rules will go to the Asset Worker. * * Can also be `true`, indicating that every request should be routed to the User Worker. */ runWorkerFirst?: string[] | boolean; }
Specify the directory of static assets to deploy/serve. More details at https://developers.cloudflare.com/workers/frameworks/ For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#assets
domains?: string[]
Custom domains that your Worker should be published to. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#types-of-routes
triggers?: Trigger[]
Event triggers — fetch routes, queue consumers, cron schedules, Email Routing addresses, and raw sockets — that invoke this Worker. Construct entries with triggers.fetch(...), triggers.queue(...), triggers.scheduled(...), triggers.email(...), or triggers.connect(...). For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers
tailConsumers?: Array<{ /** The name of the service tail events will be forwarded to. */ worker: string; /** Whether to stream tail events in real time. */ streaming?: boolean; }>
A list of Tail Workers that are bound to this Worker. @cloudflare/config unifies regular and streaming tail consumers under a single field; pass streaming: true to forward streaming tail events.
cache?: { /** If cache is enabled for this Worker. */ enabled: boolean; /** Whether cached assets may be reused across Worker versions. */ crossVersionCache?: boolean; }
Specify the cache behavior of the Worker.
placement?: { mode: "off" | "smart"; hint?: string; } | { mode?: "targeted"; region: string; } | { mode?: "targeted"; host: string; } | { mode?: "targeted"; hostname: string; }
Specify how the Worker should be located to minimize round-trip time. More details: https://developers.cloudflare.com/workers/platform/smart-placement/
limits?: { /** Maximum allowed CPU time for a Worker's invocation in milliseconds. */ cpuMs?: number; /** Maximum allowed number of fetch requests that a Worker's invocation can execute. */ subrequests?: number; }
Specify limits for runtime behavior. Only supported for the "standard" Usage Model. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#limits
logpush?: boolean
Send Trace Events from this Worker to Workers Logpush. This will not configure a corresponding Logpush job automatically. For more information about Workers Logpush, see: https://blog.cloudflare.com/logpush-for-workers/
observability?: { /** If observability is enabled for this Worker. */ enabled?: boolean; /** The sampling rate. */ headSamplingRate?: number; /** * Whether query strings are removed from request URLs in logs and traces. * * @default false */ redactQueryString?: boolean; /** Real-time Issues settings for this Worker. */ issues?: { /** Whether real-time Issues are enabled. */ enabled?: boolean; }; logs?: { enabled?: boolean; /** The sampling rate. */ headSamplingRate?: number; /** Set to false to disable invocation logs. */ invocationLogs?: boolean; /** * If logs should be persisted to the Cloudflare observability platform where they can be queried in the dashboard. * * @default true */ persist?: boolean; /** * What destinations logs emitted from the Worker should be sent to. * * @default [] */ destinations?: string[]; }; traces?: { enabled?: boolean; /** The sampling rate. */ headSamplingRate?: number; /** * If traces should be persisted to the Cloudflare observability platform where they can be queried in the dashboard. * * @default true */ persist?: boolean; /** * What destinations traces emitted from the Worker should be sent to. * * @default [] */ destinations?: string[]; }; }
Specify the observability behavior of the Worker. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#observability
workersDev?: boolean
Whether we use <name>.<subdomain>.workers.dev to test and deploy your Worker. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#workersdev
previewUrls?: boolean
Whether we use <version>-<name>.<subdomain>.workers.dev to serve Preview URLs for your Worker.
unsafe?: { /** * Arbitrary key/value pairs that will be included in the uploaded metadata. Values specified * here will always be applied to metadata last, so can add new or override existing fields. */ metadata?: Record<string, unknown>; /** * Used for internal capnp uploads for the Workers runtime. */ capnp?: { basePath: string; sourceSchemas: string[]; compiledSchema?: never; } | { basePath?: never; sourceSchemas?: never; compiledSchema: string; }; }
"Unsafe" tables for runtime features that aren't directly supported by this configuration. Values are forwarded verbatim in the Worker's upload metadata.
env?: Record<string, Binding>
Bindings exposed on the Worker's env object. Construct entries with bindings.kv(...), bindings.r2(...), etc.
exports?: Record<string, Export>
Configuration for named exports declared by the Worker. Each entry's key is the exported class name; the value configures the export. - Construct entries with exports.durableObject(...). - Declares Durable Object classes exported from this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects. - Construct entries with exports.workflow(...). - Declares Workflows defined by this Worker. For more information about Workflows, see the documentation at https://developers.cloudflare.com/workflows/.
name: "api-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

exports: { (exports reference)

exportsOptionalLink to exports

exports?: Record<string, Export>

Configuration for named exports declared by the Worker. Each entry's key is the exported class name; the value configures the export. - Construct entries with exports.durableObject(...). - Declares Durable Object classes exported from this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects. - Construct entries with exports.workflow(...). - Declares Workflows defined by this Worker. For more information about Workflows, see the documentation at https://developers.cloudflare.com/workflows/.

Admin: exports.worker(), (worker reference)

workerBuilderLink to worker

worker(options?: WorkerEntrypointExportOptions): WorkerEntrypointExport;

Declares a WorkerEntrypoint export defined by this Worker.

Options (1)
cache?: { /** Whether cache is enabled for this entrypoint. */ enabled: boolean; }
Counter: exports.durableObject({ storage: "sqlite" }), (durableObject, storage reference)

durableObjectBuilderLink to durableObject

durableObject<TContainer extends ContainerDefinition | undefined = undefined>(options: DurableObjectCreatedExportOptions<TContainer>): DurableObjectCreatedExport<TContainer>;

Declares a Durable Object class defined by this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects

Options (4)
state?: "created"
storage: "sqlite"
Selects the SQLite-backed storage engine (recommended for new classes).
container?: TContainer
Attach a Container application to this Durable Object by config reference.
storage: "legacy-kv"
Selects the legacy key-value storage engine.

storageRequiredLink to storage

storage: "sqlite" | "legacy-kv"

Selects the SQLite-backed storage engine (recommended for new classes). Selects the legacy key-value storage engine.

},
});
export default defineConfig({ worker: apiWorker }); (defineConfig, worker 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.

workerOptionalLink to worker

worker?: ConfigInput<WorkerConfig>

The Worker defined by this configuration.

第二个 Worker 可以导入该定义:

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

web/cloudflare.config.ts
import { bindings, defineConfig } from "cf/config";
import { apiWorker } from "../api/cloudflare.config.ts";
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: "web-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: bindings.worker({ (worker reference)

workerBuilderLink to worker

worker<TWorker$1 extends WorkerReference, TExportName$1 extends WorkerEntrypointExportName<TWorker$1> | undefined = undefined>(options: WorkerBindingOptions<TWorker$1, TExportName$1>): WorkerBinding<TWorker$1, NoInfer<TExportName$1>>;

Service binding (Worker-to-Worker). worker is the name or config of the bound Worker; exportName selects a named WorkerEntrypoint export (defaults to the default export). For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#service-bindings

Options (4)
worker: TWorker$1
The name or config of the bound Worker.
exportName?: TExportName$1
The named export to bind to (defaults to the default export).
props?: Record<string, unknown>
Optional properties that will be made available to the service via ctx.props.
dev?: BindingDevOptions
Options that only apply during local development.
worker: apiWorker, (worker reference)

workerRequiredLink to worker

worker: TWorker$1

The name or config of the bound Worker.

exportName: "Admin", (exportName reference)

exportNameOptionalLink to exportName

exportName?: TExportName$1

The named export to bind to (defaults to the default export).

}),
COUNTERS: bindings.durableObject({ (durableObject reference)

durableObjectBuilderLink to durableObject

durableObject<TWorker$1 extends WorkerReference, TExportName$1 extends DurableObjectExportName<TWorker$1>>(options: DurableObjectBindingOptions<TWorker$1, TExportName$1>): DurableObjectBinding<TWorker$1, TExportName$1>;

Binding to a Durable Object class. worker is the name or config of the Worker that defines the class; exportName is the exported class name. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects

Options (2)
worker: TWorker$1
The name or config of the Worker that defines the Durable Object class.
exportName: TExportName$1
The exported class name of the Durable Object.
worker: apiWorker, (worker reference)

workerRequiredLink to worker

worker: TWorker$1

The name or config of the Worker that defines the Durable Object class.

exportName: "Counter", (exportName reference)

exportNameRequiredLink to exportName

exportName: TExportName$1

The exported class name of the Durable Object.

}),
},
},
});

导入其他配置文件时,请使用其 .ts 扩展名。Node.js 使用自身的模块解析方式加载 cloudflare.config.ts,不会添加扩展名。未包含扩展名的导入会失败,并显示 Cannot find module 错误(ERR_MODULE_NOT_FOUND)。由于 API 命令也会加载最近的配置文件,此错误也会导致该目录中的普通 API 命令失败。

TypeScript 会拒绝未知的导出名称,还会从导入的入口推断 API 远程过程调用(RPC)方法和 Durable Object stub 类型。

无法导入目标定义时,使用 Worker 名称。TypeScript 可以验证绑定结构,但无法验证远程导出名称。

声明触发器

每个 triggers 方法返回带类型的事件声明。将这些值添加到 worker.triggers 数组中。

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

cloudflare.config.ts
import { defineConfig, triggers } 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: "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

triggers: [ (triggers reference)

triggersOptionalLink to triggers

triggers?: Trigger[]

Event triggers — fetch routes, queue consumers, cron schedules, Email Routing addresses, and raw sockets — that invoke this Worker. Construct entries with triggers.fetch(...), triggers.queue(...), triggers.scheduled(...), triggers.email(...), or triggers.connect(...). For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers

triggers.fetch({ (fetch reference)

fetchBuilderLink to fetch

fetch(options: FetchTriggerOptions): FetchTrigger;

Fetch trigger — a route that your Worker should be published to. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#types-of-routes

Options (2)
pattern: string
A route that your Worker should be published to. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#types-of-routes
zone?: string
The DNS zone the pattern is attached to. Required when the pattern is ambiguous.
pattern: "api.example.com/*", (pattern reference)

patternRequiredLink to pattern

pattern: string

A route that your Worker should be published to. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#types-of-routes

zone: "example.com", (zone reference)

zoneOptionalLink to zone

zone?: string

The DNS zone the pattern is attached to. Required when the pattern is ambiguous.

}),
triggers.queue({ (queue reference)

queueBuilderLink to queue

queue(options: QueueConsumerTriggerOptions): QueueConsumerTrigger;

Queue consumer trigger — invokes this Worker when messages arrive on the named queue. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#queues

Options (8)
name: string
The name of the queue from which this consumer should consume.
deadLetterQueue?: string
The queue to send messages that failed to be consumed.
maxBatchSize?: number
The maximum number of messages per batch.
maxBatchTimeout?: number
The maximum number of seconds to wait to fill a batch with messages.
maxConcurrency?: number | null
The maximum number of concurrent consumer Worker invocations. Leaving this unset will allow your consumer to scale to the maximum concurrency needed to keep up with the message backlog.
maxRetries?: number
The maximum number of retries for each message.
retryDelay?: number
The number of seconds to wait before retrying a message.
visibilityTimeoutMs?: number
The number of milliseconds to wait for pulled messages to become visible again.
name: "application-jobs", (name reference)

nameRequiredLink to name

name: string

The name of the queue from which this consumer should consume.

maxBatchSize: 10, (maxBatchSize reference)

maxBatchSizeOptionalLink to maxBatchSize

maxBatchSize?: number

The maximum number of messages per batch.

maxRetries: 3, (maxRetries reference)

maxRetriesOptionalLink to maxRetries

maxRetries?: number

The maximum number of retries for each message.

}),
triggers.scheduled({ schedule: "0 * * * *" }), (scheduled, schedule reference)

scheduledBuilderLink to scheduled

scheduled(options: ScheduledTriggerOptions): ScheduledTrigger;

Scheduled (cron) trigger — invokes this Worker on the given schedules. More details here https://developers.cloudflare.com/workers/platform/cron-triggers

Options (1)
schedule: string
A "cron" definition to trigger a Worker's "scheduled" function. Lets you call Workers periodically, much like a cron job. More details here https://developers.cloudflare.com/workers/platform/cron-triggers

scheduleRequiredLink to schedule

schedule: string

A "cron" definition to trigger a Worker's "scheduled" function. Lets you call Workers periodically, much like a cron job. More details here https://developers.cloudflare.com/workers/platform/cron-triggers

triggers.email({ addresses: ["[email protected]"] }), (email, addresses reference)

emailBuilderLink to email

email(options: EmailTriggerOptions): EmailTrigger;

Email trigger — invokes this Worker for the configured Email Routing addresses.

Options (1)
addresses: string[]
Inbound Email Routing addresses handled by this Worker. Each entry is a literal recipient address (e.g. "[email protected]") or a *@domain catch-all (e.g. "*@example.com").

addressesRequiredLink to addresses

addresses: string[]

Inbound Email Routing addresses handled by this Worker. Each entry is a literal recipient address (e.g. "[email protected]") or a *@domain catch-all (e.g. "*@example.com").

triggers.connect({ protocol: "tcp", port: 5432 }), (connect, protocol, port reference)

connectBuilderLink to connect

connect(options: ConnectTriggerOptions): ConnectTrigger;

Connect trigger — invokes this Worker's connect(socket, env, ctx) handler for raw socket connections received on the configured protocol/port.

Options (6)
port: number
The port to listen on.
address?: string
The address to bind to. Defaults to 127.0.0.1.
protocol: "tcp"
protocol: "udp"
idleTimeoutMs?: number
The idle timeout in milliseconds after which a peer flow is closed.
maxPendingBytes?: number
The maximum number of pending datagram bytes per peer flow.

protocolRequiredLink to protocol

protocol: "tcp" | "udp"

The type definition does not include a description.

portRequiredLink to port

port: number

The port to listen on.

],
},
});

构建器提供以下触发器方法:

方法 事件
fetch 路由接收 HTTP 流量
queue 队列传递消息
scheduled cron 计划运行
email Email Routing 接收匹配的电子邮件
connect TCP 或 UDP 流量到达配置的端口

在 triggers.connect() 中,将 protocol 设置为 "tcp" 或 "udp"。UDP 触发器还接受 idleTimeoutMs 和 maxPendingBytes。

触发器控制哪些事件调用 Worker。它们不会创建 env 绑定。TypeScript 检查每个触发器的选项,而 Workers 运行时类型提供处理函数签名。

声明导出

worker.exports 映射描述平台如何管理模块导出。每个键必须与 default 导出或入口导出的命名类匹配。

使用 exports.worker() 配置 WorkerEntrypoint。它接受可选的每入口缓存设置。使用 exports.durableObject() 声明 Durable Object 类及其生命周期状态。使用 exports.workflow() 声明扩展 WorkflowEntrypoint 的类。

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

cloudflare.config.ts
import { defineConfig, exports } 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: "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

exports: { (exports reference)

exportsOptionalLink to exports

exports?: Record<string, Export>

Configuration for named exports declared by the Worker. Each entry's key is the exported class name; the value configures the export. - Construct entries with exports.durableObject(...). - Declares Durable Object classes exported from this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects. - Construct entries with exports.workflow(...). - Declares Workflows defined by this Worker. For more information about Workflows, see the documentation at https://developers.cloudflare.com/workflows/.

default: exports.worker({ cache: { enabled: false } }), (worker, cache, enabled reference)

workerBuilderLink to worker

worker(options?: WorkerEntrypointExportOptions): WorkerEntrypointExport;

Declares a WorkerEntrypoint export defined by this Worker.

Options (1)
cache?: { /** Whether cache is enabled for this entrypoint. */ enabled: boolean; }

cacheOptionalLink to cache

cache?: { /** Whether cache is enabled for this entrypoint. */ enabled: boolean; }

The type definition does not include a description.

enabledRequiredLink to enabled

enabled: boolean

Whether cache is enabled for this entrypoint.

Admin: exports.worker({ cache: { enabled: true } }), (worker, cache, enabled reference)

workerBuilderLink to worker

worker(options?: WorkerEntrypointExportOptions): WorkerEntrypointExport;

Declares a WorkerEntrypoint export defined by this Worker.

Options (1)
cache?: { /** Whether cache is enabled for this entrypoint. */ enabled: boolean; }

cacheOptionalLink to cache

cache?: { /** Whether cache is enabled for this entrypoint. */ enabled: boolean; }

The type definition does not include a description.

enabledRequiredLink to enabled

enabled: boolean

Whether cache is enabled for this entrypoint.

Counter: exports.durableObject({ storage: "sqlite" }), (durableObject, storage reference)

durableObjectBuilderLink to durableObject

durableObject<TContainer extends ContainerDefinition | undefined = undefined>(options: DurableObjectCreatedExportOptions<TContainer>): DurableObjectCreatedExport<TContainer>;

Declares a Durable Object class defined by this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects

Options (4)
state?: "created"
storage: "sqlite"
Selects the SQLite-backed storage engine (recommended for new classes).
container?: TContainer
Attach a Container application to this Durable Object by config reference.
storage: "legacy-kv"
Selects the legacy key-value storage engine.

storageRequiredLink to storage

storage: "sqlite" | "legacy-kv"

Selects the SQLite-backed storage engine (recommended for new classes). Selects the legacy key-value storage engine.

OrderWorkflow: exports.workflow({ (workflow reference)

workflowBuilderLink to workflow

workflow(options: WorkflowExportOptions): WorkflowExport;

Declares a Workflow defined by this Worker. The export's key must name a class that extends WorkflowEntrypoint. For more information about Workflows, see the documentation at https://developers.cloudflare.com/workflows/

Options (5)
name: string
The name of the Workflow. It identifies the Workflow's instances and must be unique within the account.
limits?: { /** Maximum number of steps a single Workflow instance may run. */ steps?: number; }
concurrency?: { /** Maximum number of Workflow instances that can run concurrently. */ limit?: number; }
schedules?: string | string[]
Cron schedule(s) that automatically trigger Workflow instances.
defaultRetention?: { /** How long to retain instances that completed successfully or were terminated. */ successRetention?: number | string; /** How long to retain errored instances. */ errorRetention?: number | string; }
Default retention for instances of this Workflow, applied when an instance does not set its own retention. Accepts milliseconds or a duration string such as "3 days".
name: "order-workflow", (name reference)

nameRequiredLink to name

name: string

The name of the Workflow. It identifies the Workflow's instances and must be unique within the account.

limits: { steps: 100 }, (limits, steps reference)

limitsOptionalLink to limits

limits?: { /** Maximum number of steps a single Workflow instance may run. */ steps?: number; }

The type definition does not include a description.

stepsOptionalLink to steps

steps?: number

Maximum number of steps a single Workflow instance may run.

defaultRetention: { (defaultRetention reference)

defaultRetentionOptionalLink to defaultRetention

defaultRetention?: { /** How long to retain instances that completed successfully or were terminated. */ successRetention?: number | string; /** How long to retain errored instances. */ errorRetention?: number | string; }

Default retention for instances of this Workflow, applied when an instance does not set its own retention. Accepts milliseconds or a duration string such as "3 days".

successRetention: "3 days", (successRetention reference)

successRetentionOptionalLink to successRetention

successRetention?: number | string

How long to retain instances that completed successfully or were terminated.

errorRetention: "7 days", (errorRetention reference)

errorRetentionOptionalLink to errorRetention

errorRetention?: number | string

How long to retain errored instances.

},
}),
},
},
});

构建器描述导出的代码,不会创建 JavaScript 导出。入口仍必须导出 Admin、Counter 和 OrderWorkflow。

exports.workflow() 需要一个 name,并且该名称在账户中必须唯一。 它还接受 limits.steps、concurrency.limit、用于启动实例的 cron 计划 schedules、defaultRetention 和 jurisdiction。 保留期值可以使用毫秒或持续时间字符串,例如 "3 days"。 jurisdiction 限制 Workflow 实例运行和存储数据的位置, 并且在创建 Workflow 后无法更改。请参阅 数据位置。

要从同一个 Worker 或另一个 Worker 绑定到 Workflow,请使用 bindings.workflow()。它需要 Workflow 的 name、定义它的 worker(Worker 名称或 Worker 定义),以及其类的 exportName,例如 bindings.workflow({ name: "order-workflow", worker: "example-worker", exportName: "OrderWorkflow" })。

管理 Durable Object 生命周期

exports 映射替代有序的 Durable Object 迁移历史。将存活类保留在映射中。删除、重命名或转移类时,添加临时墓碑条目。

每个条目的键是 Durable Object 类名。state 字段决定有效的生命周期选项:

状态 用途
created 或省略 声明使用 sqlite 或 legacy-kv 存储的存活类
deleted 类移除后停用其命名空间
renamed 将键重命名为 renamedTo 指定的存活类名称
expecting-transfer 准备目标 Worker,以接收来自 transferFrom 的命名空间
transferred 将所有权转移给 transferredTo 指定的同账户 Worker

新类使用 sqlite。使用 sqlite 的存活类或待转入类可以附加 Container 定义。不能将 Container 附加到 legacy-kv 类或墓碑条目。

区分导出和绑定

导出和绑定的用途不同:

配置 用途
exports.Counter 声明类并管理其命名空间生命周期
env.COUNTERS 在 env.COUNTERS 下注入命名空间绑定
ctx.exports.Counter 无需 env 绑定即可访问同一 Worker 导出的类

存活的 Durable Object 导出会成为 ctx.exports 上的带类型属性。Worker 无需 env 绑定即可调用自己的类。

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

cloudflare.config.ts
import { defineConfig, exports } 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: "counter-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

compatibilityFlags: ["enable_ctx_exports"], (compatibilityFlags reference)

compatibilityFlagsOptionalLink to compatibilityFlags

compatibilityFlags?: string[]

A list of flags that enable features from upcoming features of the Workers runtime, usually used together with compatibilityDate. More details at https://developers.cloudflare.com/workers/configuration/compatibility-flags/

Default: []

exports: { (exports reference)

exportsOptionalLink to exports

exports?: Record<string, Export>

Configuration for named exports declared by the Worker. Each entry's key is the exported class name; the value configures the export. - Construct entries with exports.durableObject(...). - Declares Durable Object classes exported from this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects. - Construct entries with exports.workflow(...). - Declares Workflows defined by this Worker. For more information about Workflows, see the documentation at https://developers.cloudflare.com/workflows/.

Counter: exports.durableObject({ storage: "sqlite" }), (durableObject, storage reference)

durableObjectBuilderLink to durableObject

durableObject<TContainer extends ContainerDefinition | undefined = undefined>(options: DurableObjectCreatedExportOptions<TContainer>): DurableObjectCreatedExport<TContainer>;

Declares a Durable Object class defined by this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects

Options (4)
state?: "created"
storage: "sqlite"
Selects the SQLite-backed storage engine (recommended for new classes).
container?: TContainer
Attach a Container application to this Durable Object by config reference.
storage: "legacy-kv"
Selects the legacy key-value storage engine.

storageRequiredLink to storage

storage: "sqlite" | "legacy-kv"

Selects the SQLite-backed storage engine (recommended for new classes). Selects the legacy key-value storage engine.

},
},
});

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

export class Counter extends DurableObject {
	getValue() {
		return this.ctx.storage.get("value");
	}
}

export default {
	async fetch(_request, _env, ctx) {
		const id = ctx.exports.Counter.idFromName("global");
		const stub = ctx.exports.Counter.get(id);
		return Response.json({ value: await stub.getValue() });
	},
};
src/index.tsts
import { DurableObject } from "cloudflare:workers";

export class Counter extends DurableObject {
    getValue() {
        return this.ctx.storage.get<number>("value");
    }
}

export default {
    async fetch(_request, _env, ctx) {
        const id = ctx.exports.Counter.idFromName("global");
        const stub = ctx.exports.Counter.get(id);
        return Response.json({ value: await stub.getValue() });
    },
} satisfies ExportedHandler<Env>;

生成的类型包含存活和待转入的 Durable Object 导出。墓碑条目不会出现在 ctx.exports 上。

重命名或删除类

重命名时,将旧名称保留为墓碑条目。目标名称必须在同一映射中作为存活条目出现。请从 Worker 代码中移除旧类。

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

cloudflare.config.ts
import { defineConfig, exports } 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: "counter-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

exports: { (exports reference)

exportsOptionalLink to exports

exports?: Record<string, Export>

Configuration for named exports declared by the Worker. Each entry's key is the exported class name; the value configures the export. - Construct entries with exports.durableObject(...). - Declares Durable Object classes exported from this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects. - Construct entries with exports.workflow(...). - Declares Workflows defined by this Worker. For more information about Workflows, see the documentation at https://developers.cloudflare.com/workflows/.

Counter: exports.durableObject({ storage: "sqlite" }), (durableObject, storage reference)

durableObjectBuilderLink to durableObject

durableObject<TContainer extends ContainerDefinition | undefined = undefined>(options: DurableObjectCreatedExportOptions<TContainer>): DurableObjectCreatedExport<TContainer>;

Declares a Durable Object class defined by this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects

Options (4)
state?: "created"
storage: "sqlite"
Selects the SQLite-backed storage engine (recommended for new classes).
container?: TContainer
Attach a Container application to this Durable Object by config reference.
storage: "legacy-kv"
Selects the legacy key-value storage engine.

storageRequiredLink to storage

storage: "sqlite" | "legacy-kv"

Selects the SQLite-backed storage engine (recommended for new classes). Selects the legacy key-value storage engine.

OldCounter: exports.durableObject({ (durableObject reference)

durableObjectBuilderLink to durableObject

durableObject(options: DurableObjectRenamedExportOptions): DurableObjectRenamedExport;

Rename a provisioned Durable Object namespace's class.

Options (2)
state: "renamed"
renamedTo: string
The destination class name. Must be a valid JavaScript identifier and must appear as a live (state: "created") durableObject entry in the same exports map.
state: "renamed", (state reference)

stateRequiredLink to state

state: "renamed"

The type definition does not include a description.

renamedTo: "Counter", (renamedTo reference)

renamedToRequiredLink to renamedTo

renamedTo: string

The destination class name. Must be a valid JavaScript identifier and must appear as a live (state: "created") durableObject entry in the same exports map.

}),
UnusedCounter: exports.durableObject({ state: "deleted" }), (durableObject, state reference)

durableObjectBuilderLink to durableObject

durableObject(options: DurableObjectDeletedExportOptions): DurableObjectDeletedExport;

Retire a provisioned Durable Object namespace whose class has been removed from code.

Options (1)
state: "deleted"

stateRequiredLink to state

state: "deleted"

The type definition does not include a description.

},
},
});

删除命名空间前,移除指向该类的所有绑定。上传的 Worker 不能导出标记为 deleted 的类。

部署响应会标识可安全移除的过期墓碑条目。每个墓碑条目都应保留到它出现在该响应中,再将其从映射移除。无需保留完整迁移历史。

在 Workers 之间转移类

命名空间转移需要两次部署。两个 Worker 必须使用同一个 Cloudflare 账户。

首先,在目标 Worker 中添加待转入的存活条目并部署:

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

destination/cloudflare.config.ts
import { defineConfig, exports } 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: "destination-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

exports: { (exports reference)

exportsOptionalLink to exports

exports?: Record<string, Export>

Configuration for named exports declared by the Worker. Each entry's key is the exported class name; the value configures the export. - Construct entries with exports.durableObject(...). - Declares Durable Object classes exported from this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects. - Construct entries with exports.workflow(...). - Declares Workflows defined by this Worker. For more information about Workflows, see the documentation at https://developers.cloudflare.com/workflows/.

Counter: exports.durableObject({ (durableObject reference)

durableObjectBuilderLink to durableObject

durableObject<TContainer extends ContainerDefinition | undefined = undefined>(options: DurableObjectExpectingTransferExportOptions<TContainer>): DurableObjectExpectingTransferExport<TContainer>;

Prepare to receive cross-Worker Durable Object transfer. The source Worker must follow up with a deployment containing a transferred export to commit the transfer.

Options (5)
state: "expecting-transfer"
transferFrom: string
The source Worker for the two-phase cross-Worker transfer.
storage: "sqlite"
Selects the SQLite-backed storage engine (recommended for new classes).
container?: TContainer
Attach a Container application to this Durable Object by config reference.
storage: "legacy-kv"
Selects the legacy key-value storage engine.
state: "expecting-transfer", (state reference)

stateRequiredLink to state

state: "expecting-transfer"

The type definition does not include a description.

storage: "sqlite", (storage reference)

storageRequiredLink to storage

storage: "sqlite" | "legacy-kv"

Selects the SQLite-backed storage engine (recommended for new classes). Selects the legacy key-value storage engine.

transferFrom: "source-worker", (transferFrom reference)

transferFromRequiredLink to transferFrom

transferFrom: string

The source Worker for the two-phase cross-Worker transfer.

}),
},
},
});

然后,在源 Worker 中添加转移墓碑条目并部署:

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

source/cloudflare.config.ts
import { defineConfig, exports } 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: "source-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

exports: { (exports reference)

exportsOptionalLink to exports

exports?: Record<string, Export>

Configuration for named exports declared by the Worker. Each entry's key is the exported class name; the value configures the export. - Construct entries with exports.durableObject(...). - Declares Durable Object classes exported from this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects. - Construct entries with exports.workflow(...). - Declares Workflows defined by this Worker. For more information about Workflows, see the documentation at https://developers.cloudflare.com/workflows/.

Counter: exports.durableObject({ (durableObject reference)

durableObjectBuilderLink to durableObject

durableObject(options: DurableObjectTransferredExportOptions): DurableObjectTransferredExport;

Transfer ownership of a Durable Object namespace to another Worker in the same account.

Options (2)
state: "transferred"
transferredTo: string
The destination Worker. Must reference a Worker in the same account.
state: "transferred", (state reference)

stateRequiredLink to state

state: "transferred"

The type definition does not include a description.

transferredTo: "destination-worker", (transferredTo reference)

transferredToRequiredLink to transferredTo

transferredTo: string

The destination Worker. Must reference a Worker in the same account.

}),
},
},
});

生命周期变更在部署版本时生效,上传时不会生效。在与其他版本分流之前,将更改导出的版本部署到 100% 流量。平台会拒绝 exports 不一致的版本之间的分流部署。

附加 Container

只定义一次 Container。从 Durable Object 导出引用它,并将其添加到顶级 containers 数组中。

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

cloudflare.config.ts
import { bindings, defineConfig, defineContainer, exports } from "cf/config";
import * as entrypoint from "./src/index.ts" with { type: "cf-worker" };
const imageProcessor = defineContainer({ (defineContainer reference)

defineContainerFunctionLink to defineContainer

defineContainer<T extends ConfigInput<ContainerConfig>>(config: T): T;

Defines a Container application that you can list in containers in defineConfig() or attach to a Durable Object export with its container option.

name: "image-processor",
image: { dockerfile: "./Dockerfile" },
instanceType: "lite",
maxInstances: 1,
});
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: "image-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

exports: { (exports reference)

exportsOptionalLink to exports

exports?: Record<string, Export>

Configuration for named exports declared by the Worker. Each entry's key is the exported class name; the value configures the export. - Construct entries with exports.durableObject(...). - Declares Durable Object classes exported from this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects. - Construct entries with exports.workflow(...). - Declares Workflows defined by this Worker. For more information about Workflows, see the documentation at https://developers.cloudflare.com/workflows/.

ImageProcessor: exports.durableObject({ (durableObject reference)

durableObjectBuilderLink to durableObject

durableObject<TContainer extends ContainerDefinition | undefined = undefined>(options: DurableObjectCreatedExportOptions<TContainer>): DurableObjectCreatedExport<TContainer>;

Declares a Durable Object class defined by this Worker. For more information about Durable Objects, see the documentation at https://developers.cloudflare.com/workers/learning/using-durable-objects For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects

Options (4)
state?: "created"
storage: "sqlite"
Selects the SQLite-backed storage engine (recommended for new classes).
container?: TContainer
Attach a Container application to this Durable Object by config reference.
storage: "legacy-kv"
Selects the legacy key-value storage engine.
storage: "sqlite", (storage reference)

storageRequiredLink to storage

storage: "sqlite" | "legacy-kv"

Selects the SQLite-backed storage engine (recommended for new classes). Selects the legacy key-value storage engine.

container: imageProcessor, (container reference)

containerOptionalLink to container

container?: TContainer

Attach a Container application to this Durable Object by config reference.

}),
},
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.

IMAGE_PROCESSOR: bindings.durableObject({ (durableObject reference)

durableObjectBuilderLink to durableObject

durableObject<TWorker$1 extends WorkerReference, TExportName$1 extends DurableObjectExportName<TWorker$1>>(options: DurableObjectBindingOptions<TWorker$1, TExportName$1>): DurableObjectBinding<TWorker$1, TExportName$1>;

Binding to a Durable Object class. worker is the name or config of the Worker that defines the class; exportName is the exported class name. For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#durable-objects

Options (2)
worker: TWorker$1
The name or config of the Worker that defines the Durable Object class.
exportName: TExportName$1
The exported class name of the Durable Object.
worker: "image-worker", (worker reference)

workerRequiredLink to worker

worker: TWorker$1

The name or config of the Worker that defines the Durable Object class.

exportName: "ImageProcessor", (exportName reference)

exportNameRequiredLink to exportName

exportName: TExportName$1

The exported class name of the Durable Object.

}),
},
},
containers: [imageProcessor], (containers reference)

containersOptionalLink to containers

containers?: ConfigInput<ContainerConfig>[]

Container applications defined by this configuration.

});

Container 名称必须唯一。每个 Container 只能链接到一个 Durable Object 导出。

cf deploy 会应用受支持的 Container 应用变更。 cf workers versions create 为由 Durable Object 管理的 Containers 准备镜像,但不会应用 Container 应用。

设置账户默认值

在默认导出的顶级设置 accountId 和 complianceRegion。受支持的合规区域为 public 和 fedramp-high。

CLOUDFLARE_ACCOUNT_ID 和 CLOUDFLARE_COMPLIANCE_REGION 优先于这些值。环境和配置都未设置账户时,cf 会使用在先前命令中保存的账户,或根据凭证解析账户。完整优先顺序请参阅选择账户。

cf 从当前目录向文件系统根目录搜索,使用最近的 cloudflare.config.ts 文件。

API 命令读取账户默认值时,cf 会执行模块并解析默认导出。如果默认导出是函数,cf 会以 isPreview: false 和通过 --mode 传入的模式调用它。未指定 --mode 时,模式为 undefined,而同一项目的 Vite 构建使用 production。cf deploy、cf workers versions create 和 cf workers triggers deploy 以相同方式解析账户。未指定 --mode 时,即使 Vite 构建使用 production,它们也会以 undefined 模式求值配置。如果 accountId 取决于模式,请为每个命令显式传入 --mode。

API 命令不会求值嵌套的 worker 或 containers 工厂,也不会验证 Worker 字段。模块中的语法错误、导入错误和顶级运行时错误仍会导致这些命令失败。

选择模式

传入 --mode <NAME> 或 -m <NAME>,为指定模式求值函数形式的配置。项目命令也会将模式传递给构建:

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

省略 --mode 时,默认值取决于求值配置的工具:

命令 默认模式
使用 Cloudflare Vite 插件的 cf dev development
cf build、cf deploy 和其他使用 Vite 构建的命令 production
使用 Wrangler 构建的命令 undefined
API 命令,例如 cf d1 list undefined

cf 运行框架自身的命令时,只有 Vite 和 Astro 接受 --mode。对于其他框架,命令会停止,并报错说明检测到的命令目前不支持 --mode。

Build Output 在其根目录的 config.json 中记录模式。要使用 --prebuilt 部署现有构建,请传入所记录的模式。规则和示例请参阅部署预构建输出。

这篇文档对您有帮助吗?