React ↗ 是用于构建用户界面的框架。它允许你创建可复用的 UI 组件并高效管理应用状态。你可以使用 React 构建单页应用(SPA),并将其与运行在 Cloudflare Workers 上的后端 API 结合,创建全栈应用。
本指南说明如何将 React + Vite 应用部署到 Cloudflare Workers。你可以使用 create-cloudflare CLI(C3)创建新项目,或适配现有 React + Vite 项目。
从 CLI 开始 — 使用 React SPA、Cloudflare Workers API 和 Cloudflare Vite 插件 搭建全栈应用,获得极速开发体验。
npm create cloudflare@latest -- my-react-app --framework=reactyarn create cloudflare my-react-app --framework=reactpnpm create cloudflare@latest my-react-app --framework=react或直接部署 — 使用 React、Workers API 和 Vite 创建全栈应用,CI/CD 与预览均已为你配置好。
-
使用 create-cloudflare CLI (C3) 创建新项目
npm create cloudflare@latest -- my-react-app --framework=reactyarn create cloudflare my-react-app --framework=reactpnpm create cloudflare@latest my-react-app --framework=react此项目是如何设置的?
以下是项目的简化文件树。
- my-react-app
- src/
- App.tsx
- worker/
- index.ts
- index.html
- vite.config.ts
- wrangler.jsonc
- src/
wrangler.jsonc是你的 Wrangler 配置文件。 在此文件中:main指向worker/index.ts。这是你的 Worker,将作为后端 API。assets.not_found_handling设置为single-page-application,意味着由 React SPA 处理的路由不会进入 Worker,因此免费。- 若要为 Cloudflare 开发者平台资源添加绑定(binding),在此配置。阅读更多关于绑定(binding)的信息。
vite.config.ts配置为使用 Cloudflare Vite 插件。这会在 Cloudflare Workers 运行时中运行 Worker,确保本地开发环境尽可能接近生产环境。worker/index.ts是后端 API,包含单个端点/api/,返回文本响应。 在src/App.tsx中,React 应用调用此端点获取消息并显示。 - my-react-app
-
使用 Cloudflare Vite 插件 在本地开发
创建项目后,在项目目录中运行以下命令以启动本地开发服务器。
npm run devyarn run devpnpm run dev本地开发中发生了什么?
此项目使用 Vite 进行本地开发和构建,因此具备 Vite 的所有功能,包括热模块替换(HMR)。
此外,
vite.config.ts配置为使用 Cloudflare Vite 插件。这会在 Cloudflare Workers 运行时中运行应用,与生产环境一致,并支持访问绑定的本地模拟。 -
部署项目
你可以从本地机器或任何 CI/CD 系统(包括 Cloudflare 自有的 Workers Builds)将项目部署到
*.workers.dev子域或自定义域名。以下命令将构建并部署项目。若使用 CI,请确保相应更新你的 「deploy command」 配置。
npm run deployyarn run deploypnpm run deploy
如果你已有 React + Vite 应用,可以使用 Cloudflare Vite 插件将其适配并部署到 Cloudflare Workers。此方法保留现有代码,同时增加部署到 Cloudflare 边缘网络的能力,包括静态资源和可选的 API Worker。
-
进入项目目录
在你选择的编辑器中打开现有 React + Vite 项目。如果还没有,请先使用 Vite 搭建新项目:
npm create vite@latest -- my-react-app --template react-tsyarn create vite my-react-app --template react-tspnpm create vite@latest my-react-app --template react-ts然后在你选择的编辑器中打开
my-react-app目录。 -
添加 Cloudflare Vite 插件
npm i -D @cloudflare/vite-plugin wrangleryarn add -D @cloudflare/vite-plugin wranglerpnpm add -D @cloudflare/vite-plugin wranglerbun add -d @cloudflare/vite-plugin wrangler在
vite.config.ts中,将 Cloudflare Vite 插件添加到框架插件之后:vite.config.tsts import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { cloudflare } from "@cloudflare/vite-plugin"; export default defineConfig({ plugins: [react(), cloudflare({ viteEnvironment: { name: "worker" } })], environments: { worker: { build: { sourcemap: true } }, }, });Cloudflare Vite 插件会在应用程序根目录中查找
wrangler.jsonc、wrangler.json或wrangler.toml。worker环境会为 Worker 生成源映射。客户端环境保留现有的源映射设置。配置选项请参阅 API 参考。
-
添加 Wrangler 配置文件
在项目根目录创建
wrangler.jsonc文件:{ "$schema": "./node_modules/wrangler/config-schema.json", "name": "my-app", // Set this to today's date "compatibility_date": "2026-11-20", "assets": { "not_found_handling": "single-page-application" } }name = "my-app" # Set this to today's date compatibility_date = "2026-11-20" [assets] not_found_handling = "single-page-application"not_found_handling的值已设置为single-page-application。 这意味着所有未找到匹配资源的请求都会返回index.html文件,这是 React Router 和其他客户端路由方案所需的行为。使用 Cloudflare 插件时,
assets路由配置会替代 Vite 的默认行为。 这确保应用的路由配置在开发期间与部署到生产环境后的行为一致。使用 Vite 配置资源时,不使用
directory字段。 输出配置中的directory会自动指向客户端构建输出。 更多信息请参阅静态资源。 -
更新
.gitignore文件开发 Workers 时,会使用或生成不应存入 Git 的额外文件。 将以下内容添加到
.gitignore文件中:.gitignoretxt .wrangler .dev.vars* -
本地开发
运行框架的开发命令,启动 Vite 开发服务器,并验证应用是否按预期工作。
npm run devyarn run devpnpm run dev对于纯前端应用,你现在就可以构建、预览和部署应用。 以下各节将介绍如何进一步添加 API Worker。
-
构建并部署项目
运行构建命令来构建应用。
npm run buildyarn run buildpnpm run builddist目录中的client子目录将包含客户端构建输出,Worker 代码和输出的wrangler.json配置文件也会位于该目录中。运行预览命令,验证应用是否按预期运行。
npm run previewyarn run previewpnpm run preview此命令会在本地 Workers 运行时中运行构建输出,其行为与生产环境高度一致。
运行部署命令,将应用部署到 Cloudflare。
npx wrangler deployyarn wrangler deploypnpm wrangler deploy此命令会自动使用构建输出中包含的
wrangler.json文件。
如果要为现有 React + Vite 项目添加 API Worker,请按以下额外步骤操作:
-
为 Worker 代码配置 TypeScript
npm i -D @cloudflare/workers-typesyarn add -D @cloudflare/workers-typespnpm add -D @cloudflare/workers-typesbun add -d @cloudflare/workers-types创建
tsconfig.worker.json,扩展 Node TypeScript 配置并添加 Workers 类型:tsconfig.worker.jsonjsonc { "extends": "./tsconfig.node.json", "compilerOptions": { "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.worker.tsbuildinfo", "types": ["@cloudflare/workers-types/2023-07-01", "vite/client"], }, "include": ["worker"], }然后在根目录的
tsconfig.json中添加对此新配置的引用:tsconfig.jsonjsonc { "files": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }, { "path": "./tsconfig.worker.json" }, ], } -
将 Worker 入口点添加到配置
更新 Wrangler 配置文件,添加指向 Worker 入口的
main字段:{ "$schema": "./node_modules/wrangler/config-schema.json", "name": "my-app", // Set this to today's date "compatibility_date": "2026-11-20", "main": "./worker/index.ts", "upload_source_maps": true, "assets": { "not_found_handling": "single-page-application" } }name = "my-app" # Set this to today's date compatibility_date = "2026-11-20" main = "./worker/index.ts" upload_source_maps = true [assets] not_found_handling = "single-page-application"main字段指定 Worker 代码的入口文件。 -
添加 API Worker
创建
worker/index.ts文件,内容如下:worker/index.tsts export default { fetch(request) { const url = new URL(request.url); if (url.pathname.startsWith("/api/")) { return Response.json({ name: "Cloudflare", }); } return new Response(null, { status: 404 }); }, } satisfies ExportedHandler;上述代码块定义的 Worker 会处理所有不匹配静态资源的非导航请求。 如果
pathname以/api/开头,则返回 JSON 响应,否则返回404响应。 -
从客户端调用 API
现在可以从 React 组件调用 API。例如,在
src/App.tsx中:src/App.tsxtsx import { useState } from "react"; function App() { const [name, setName] = useState("unknown"); return ( <div className="card"> <button onClick={() => { fetch("/api/") .then((res) => res.json() as Promise<{ name: string }>) .then((data) => setName(data.name)); }} > Name from API is: {name} </button> </div> ); } export default App;
若将 React 用作 SPA,应在 Wrangler 配置文件中将 not_found_handling = "single-page-application"。
默认情况下,Cloudflare 首先尝试将请求路径与静态资源路径匹配,该路径基于上传资源目录的文件结构。这要么是 Wrangler 配置中 assets.directory 指定的目录,要么在使用 Cloudflare Vite 插件时是客户端构建的输出目录。如果失败,且存在 Worker,则调用 Worker。如果没有 Worker,或者 Worker 随后使用 asset 绑定,Cloudflare 将回退到 not_found_handling 设置的行为。
请参阅路由文档,了解静态资源路由的工作原理以及如何自定义此行为。
项目还可以包含位于 ./worker/index.ts 的 Worker,可用作 React 应用的后端 API。React 应用无法直接访问 Workers 绑定(binding),但可以通过此 Worker 与它们交互。你可以从 React 应用向 Worker 发起 fetch() 请求,Worker 随后处理请求并使用绑定(binding)。了解如何配置 Workers 绑定(binding)。
通过绑定(binding),你的应用程序可以与 Cloudflare Developer Platform 完全集成,让你访问计算、存储、AI 等功能。