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

教程 - 带 API 的 React SPA

最后更新 查看 MarkdownAgent 设置

本教程将引导你完成将 Vite 项目适配为使用 Cloudflare Vite 插件的步骤。 大部分内容也适用于适配现有 Vite 项目以及 React 以外的其他前端框架。

简介

在本教程中,你将创建一个可部署为带静态资源的 Worker 的 React SPA。 然后添加一个可从前端代码访问的 API Worker。 你将使用 Vite 开发、构建和预览应用程序,最后部署到 Cloudflare。

设置并配置 React SPA

搭建 Vite 项目

首先使用 Vite 创建 React TypeScript 项目。

npm create vite@latest -- cloudflare-vite-tutorial --template react-ts

接下来,在你选择的编辑器中打开 cloudflare-vite-tutorial 目录。

添加 Cloudflare 依赖

npm i -D @cloudflare/vite-plugin wrangler

将 Cloudflare Vite 插件添加到项目

在 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 生成源映射。客户端环境保留现有的源映射设置。

创建 Worker 配置文件

在项目根目录创建 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 dev

对于纯前端应用,你现在就可以构建、预览和部署应用。 以下各节将介绍如何进一步添加 API Worker。

添加 API Worker

添加 Workers TypeScript 类型

npm i -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 响应。

从 client 调用 API

编辑 src/App.tsx,添加一个调用 API 并设置状态的按钮:

src/App.tsxtsx
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";

function App() {
	const [count, setCount] = useState(0);
	const [name, setName] = useState("unknown");

	return (
		<>
			<div>
				<a href="https://vite.dev" target="_blank">
					<img src={viteLogo} className="logo" alt="Vite logo" />
				</a>
				<a href="https://react.dev" target="_blank">
					<img src={reactLogo} className="logo react" alt="React logo" />
				</a>
			</div>
			<h1>Vite + React</h1>
			<div className="card">
				<button
					onClick={() => setCount((count) => count + 1)}
					aria-label="increment"
				>
					count is {count}
				</button>
				<p>
					Edit <code>src/App.tsx</code> and save to test HMR
				</p>
			</div>
			<div className="card">
				<button
					onClick={() => {
						fetch("/api/")
							.then((res) => res.json() as Promise<{ name: string }>)
							.then((data) => setName(data.name));
					}}
					aria-label="get name"
				>
					Name from API is: {name}
				</button>
				<p>
					Edit <code>api/index.ts</code> to change the name
				</p>
			</div>
			<p className="read-the-docs">
				Click on the Vite and React logos to learn more
			</p>
		</>
	);
}

export default App;

现在,如果点击按钮,将显示「Name from API is: Cloudflare」。

增加计数器以更新浏览器中的应用程序状态。 接下来,通过将返回的 name 更改为 'Cloudflare Workers' 来编辑 api/index.ts。 如果再次点击按钮,将显示新的 name,同时保留之前设置的计数器值。

使用 Vite 和 Cloudflare 插件,可以在编辑之间迭代应用程序的 client 和 server 部分,而不会丢失 UI 状态。

构建应用

运行构建命令来构建应用。

npm run build

dist 目录中的 client 子目录将包含客户端构建输出,Worker 代码和输出的 wrangler.json 配置文件也会位于该目录中。

预览应用

运行预览命令,验证应用是否按预期运行。

npm run preview

此命令会在本地 Workers 运行时中运行构建输出,其行为与生产环境高度一致。

部署到 Cloudflare

运行部署命令,将应用部署到 Cloudflare。

npx wrangler deploy

此命令会自动使用构建输出中包含的 wrangler.json 文件。

后续步骤

在本教程中,我们创建了一个可部署为带静态资源的 Worker 的 SPA。 然后添加了一个可从前端代码访问的 API Worker。 最后,我们将应用程序的 client 和 server 部分部署到 Cloudflare。

可能的后续步骤包括:

这篇文档对您有帮助吗?