@cloudflare/pages-functions

中文文档
0.1.7发布于 2026/11/09MIT OR Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 8327

Compile a Pages Functions directory into a Cloudflare Worker bundle

原始使用文档
文档目录9 节
  1. Installation
  2. CLI
  3. CLI options
  4. Programmatic API
  5. Build options
  6. Build result
  7. Migrate to Workers
  8. Contributing
  9. License

@cloudflare/pages-functions

@cloudflare/pages-functions compiles a Cloudflare Pages Functions functions/ directory into a single Cloudflare Worker bundle. It provides both a command-line interface and a programmatic API for build tools.

The package discovers file-based routes, bundles their handlers into an ES module Worker, collects imported Wasm, text, and binary modules, and returns Pages routing metadata through its programmatic API.

[!WARNING] Pages Functions are not recommended for new development. Build new applications and new server-side functionality with Workers instead. This package is intended to support existing Pages Functions projects and help migrate them incrementally to Workers.

Installation

Install the package as a development dependency:

npm install --save-dev @cloudflare/pages-functions

CLI

Compile the default functions/ directory into dist/:

npx @cloudflare/pages-functions build

To specify the input and output directories:

npx @cloudflare/pages-functions build ./functions --outdir ./dist/worker

The command writes the following files:

  • index.js: the compiled ES module Worker
  • index.js.map: the source map, when --sourcemap is used
  • Imported Wasm, text, binary, and assets: modules required by the Worker

The generated Worker contains its own router and does not require a _routes.json file. To produce one (for example when deploying to Pages), pass --routes-output <path>. Pages deployment tools such as Wrangler generate this file on their own and do not need it from the CLI.

The command only builds the Worker. It does not deploy it or create deployment configuration. By default, the generated Worker falls back to env.ASSETS.fetch() when no Function route handles a request, so the deployment must provide an ASSETS binding or select another binding with --fallback-service.

Runtime-native imports such as node:* and cloudflare:* are not automatically excluded from the bundle. Pass them through with repeatable --external options when the surrounding Worker build or runtime provides them:

npx @cloudflare/pages-functions build --external "node:*" --external "cloudflare:*"

CLI options

OptionDescriptionDefault
[directory]Pages Functions directoryfunctions
--outdir <path>Output directorydist
--minifyMinify the Worker bundleDisabled
--sourcemapGenerate an external source mapDisabled
--fallback-service <name>Fetcher binding used when no route handles the requestASSETS
--external <module>Exclude a module from the bundle; may be repeatedNone
--routes-output <path>Write the generated _routes.json spec to this pathNot written
-h, --helpDisplay usage information
-v, --versionDisplay the package version

Programmatic API

Use buildPagesFunctions() when integrating the compiler into another build tool:

import { buildPagesFunctions } from "@cloudflare/pages-functions";

const result = await buildPagesFunctions({
    functionsDirectory: "./functions",
    outputDirectory: "./dist/worker",
    sourcemap: true,
});

console.log(result.entryPointPath);
console.log(result.routesJSON);

buildPagesFunctions() returns the generated routing specification as routesJSON but does not write a _routes.json file. Consumers such as Wrangler can use this metadata when deploying to Pages.

Build options

OptionTypeDescriptionDefault
functionsDirectorystringPages Functions directory to compileRequired
outputDirectorystringDirectory for index.js and collected modulesRequired
assetsOutputDirectorystringDirectory for files referenced by assets: importsoutputDirectory
fallbackServicestringFetcher binding used when no route handles the requestASSETS
minifybooleanMinify the Worker bundlefalse
sourcemapbooleanGenerate an external source mapfalse
externalstring[]Module specifiers to exclude from the bundleundefined
routesDescriptionstringDescription included in the returned routes specificationundefined
metafilebooleanInclude the esbuild metafile in the resultfalse

Build result

buildPagesFunctions() returns:

PropertyDescription
entryPointPathAbsolute path to the generated index.js
bundleTypeAlways "esm"
modulesCollected Wasm, text, and binary modules
dependenciesInputs included in the generated bundle
sourceMapPathAbsolute source map path when source maps are enabled
routesJSONGenerated _routes.json data
filepathRoutingConfigDiscovered Pages Functions routes and base URL
metafileesbuild metafile when requested

The package also exports lower-level route discovery, generation, optimization, and validation helpers for tooling authors. Their TypeScript declarations are included with the package.

Migrate to Workers

Workers Static Assets supports deploying front-end assets and Worker code together. Workers also provides access to more Cloudflare platform features than Pages Functions. New routes and application logic should therefore be written in a Worker rather than added to an existing functions/ directory.

For an existing Pages Functions project, you can compile the old Functions during the Worker build and delegate requests to them from your Worker. This lets you migrate one route at a time.

For example, configure Wrangler to compile the legacy functions/ directory before it bundles the Worker:

{
    "$schema": "./node_modules/wrangler/config-schema.json",
    "name": "my-worker",
    "main": "./src/index.js",
    // Preserve the compatibility date and flags from your Pages project.
    "compatibility_date": "<YOUR_EXISTING_COMPATIBILITY_DATE>",
    "assets": {
        "directory": "./dist/client",
        "binding": "ASSETS",
        "run_worker_first": true,
    },
    "build": {
        "command": "npx @cloudflare/pages-functions build ./functions --outdir ./dist/pages-functions --external \"node:*\" --external \"cloudflare:*\"",
        "watch_dir": ["./functions", "./src"],
    },
}

Adjust assets.directory and combine the build command with your existing front-end build command as needed. Preserve any compatibility flags used by the Pages project. The --external options leave runtime-native imports for Wrangler to process. The ASSETS binding is required by the compiler's default fallback behavior. run_worker_first ensures the Worker can run Pages Functions routes and middleware before falling back to static assets.

Import the compiled handler from your Worker, handle new or migrated routes first, and use the old Pages Functions handler as a fallback:

import legacyPagesFunctions from "../dist/pages-functions/index.js";

export default {
    async fetch(request, env, ctx) {
        const url = new URL(request.url);

        if (url.pathname === "/api/new-route") {
            return new Response("Handled by the Worker");
        }

        return legacyPagesFunctions.fetch(request, env, ctx);
    },
};

This ordering means Pages Functions middleware does not run for routes handled directly by the Worker. Migrate authentication, authorization, logging, and other applicable middleware to the Worker before moving routes that depend on it.

As routes are migrated, remove their files from functions/ and implement them directly in the Worker. Once no legacy Pages Functions remain, remove the compiler build step and import.

If the legacy Functions use assets: imports, the imported assets must be written into the directory configured by assets.directory. The CLI writes them beneath its output directory, so use the programmatic API to select separate Worker and asset outputs:

// scripts/build-pages-functions.mjs
import { buildPagesFunctions } from "@cloudflare/pages-functions";

await buildPagesFunctions({
    functionsDirectory: "./functions",
    outputDirectory: "./dist/pages-functions",
    assetsOutputDirectory: "./dist/client",
    external: ["node:*", "cloudflare:*"],
});

Then set build.command to node ./scripts/build-pages-functions.mjs. The assets: integration always uses the ASSETS binding, even when a different general fallback service is configured.

Workers do not use Pages _routes.json metadata. Configure Workers Static Assets routing explicitly, especially if the Pages project used custom _routes.json rules or middleware. See the complete Pages-to-Workers migration guide for bindings, assets, compatibility settings, and deployment changes.

Contributing

See the Workers SDK contributing guide for repository setup and contribution requirements.

From the repository root, install dependencies and run package tasks with:

pnpm install
pnpm run build --filter @cloudflare/pages-functions
pnpm run check:type --filter @cloudflare/pages-functions
pnpm run test:ci --filter @cloudflare/pages-functions
pnpm run dev --filter @cloudflare/pages-functions

The dev task watches this package's implementation; it does not watch an end-user Pages Functions project.

Before submitting changes, run:

pnpm prettify
pnpm check

License

Licensed under either the Apache 2.0 license or the MIT license at your option.

版本与发布记录

@cloudflare/pages-functions 共发布 10 个版本,首次发布于 2026/07/30;过去 12 个月发布了 10 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.7latest2026/11/09今天
0.1.62026/11/054 天前
0.1.52026/11/036 天前
0.1.42026/11/027 天前
0.1.32026/11/028 天前
0.1.22026/10/2614 天前

关于 @cloudflare/pages-functions 的常见问题

@cloudflare/pages-functions 是什么?

Compile a Pages Functions directory into a Cloudflare Worker bundle

如何安装 @cloudflare/pages-functions?

在项目目录运行 npm install @cloudflare/pages-functions,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 pages-functions,可以用 npx pages-functions 直接运行。

@cloudflare/pages-functions 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cloudflare/pages-functions 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@cloudflare/pages-functions 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cloudflare/pages-functions 可以商用吗?

@cloudflare/pages-functions 使用 MIT OR Apache-2.0 许可。可在 MIT、Apache-2.0 中任选其一遵守。选择 MIT 时,宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cloudflare/pages-functions 的下载量有多少?

根据 npm 官方下载统计,@cloudflare/pages-functions 在 2026/10/10 – 2026/11/08 这 30 天内被下载 8,327 次,日均约 278 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cloudflare/pages-functions 还在维护吗?

最新版本 0.1.7 发布于 2026/11/09(今天);至今共发布 10 个版本,其中过去 12 个月发布了 10 个;首次发布于 2026/07/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。