跳转到内容
搜索文档

高级模式

最后更新 查看 MarkdownAgent 设置

高级模式允许你使用 _worker.js 文件而非 /functions 目录开发 Pages Functions。

在某些情况下,Pages Functions 内置的基于文件路径的路由和中间件系统不适合现有应用。你可能有一个复杂的 Worker,难以拆分到 Pages 的基于文件的路由系统中。针对这些情况,Pages 允许在 Pages 项目输出目录中定义 _worker.js 文件。

使用 _worker.js 文件时,整个 /functions 目录(包括其路由和中间件特性)将被忽略。取而代之的是部署 _worker.js 文件,且必须使用 Module Worker 语法 编写。若从未使用过 Module 语法,请参阅 JavaScript 模块博客文章 了解更多。使用 Module 语法使 JavaScript 框架能够作为 Pages 输出目录内容的一部分生成 Worker。

设置 Function

在高级模式下,Function 将完全控制发往你域名的所有 HTTP 请求。Function 必须发出或转发对项目静态资源的请求。否则会导致损坏或异常行为。Function 必须使用 Module 语法编写。

在输出目录中创建 _worker.js 文件后,添加以下代码片段:

export default {
	async fetch(request, env) {
		const url = new URL(request.url);
		if (url.pathname.startsWith("/api/")) {
			// TODO: Add your custom /api/* logic here.
			return new Response("Ok");
		}
		// Otherwise, serve the static assets.
		// Without this, the Worker will error and no assets will be served.
		return env.ASSETS.fetch(request);
	},
};
// Note: You would need to compile your TS into JS and output it as a `_worker.js` file. We do not read `_worker.ts`

interface Env {
	ASSETS: Fetcher;
}

export default {
	async fetch(request, env): Promise<Response> {
		const url = new URL(request.url);
		if (url.pathname.startsWith("/api/")) {
			// TODO: Add your custom /api/* logic here.
			return new Response("Ok");
		}
		// Otherwise, serve the static assets.
		// Without this, the Worker will error and no assets will be served.
		return env.ASSETS.fetch(request);
	},
} satisfies ExportedHandler<Env>;

在上述代码中,你已配置 Function 对所有发往 /api/ 的请求返回响应。否则,Function 将回退到返回静态资源。

  • env.ASSETS.fetch() 函数允许你在给定请求上返回资源。
  • env 是包含环境变量和绑定的对象。
  • ASSETS 是默认 Function 绑定,允许 Function 与 Pages 的资源提供资源通信。
  • fetch() 调用 Pages 的资源提供资源并提供请求的资源。

从 Workers 迁移

若要将现有 Worker 迁移到 Pages 项目,复制 Worker 代码并粘贴到新的 _worker.js 文件中。然后通过向 _worker.js 添加以下代码片段来处理静态资源:

return env.ASSETS.fetch(request);

部署 Function

设置新 Function 或将 Worker 迁移到 _worker.js 后,确保 _worker.js 文件位于 Pages 项目输出目录中。通过 Git 集成部署项目以使高级模式生效。

这篇文档对您有帮助吗?