[ PROMPT_NODE_24180 ]
Pages Functions 配置说明
[ SKILL_DOCUMENTATION ]
# 配置
## TypeScript 设置
**从 wrangler.jsonc 生成类型** (替换已弃用的 `@cloudflare/workers-types`):
bash
npx wrangler types
根据您的绑定创建包含 `Env` 接口的 `worker-configuration.d.ts`。
typescript
// functions/api.ts
export const onRequest: PagesFunction = async (ctx) => {
// ctx.env.KV, ctx.env.DB 等均具有完整类型
return Response.json({ ok: true });
};
**手动类型** (如果不使用 wrangler types):
typescript
interface Env {
KV: KVNamespace;
DB: D1Database;
API_KEY: string;
}
export const onRequest: PagesFunction = async (ctx) => { /* ... */ };
## wrangler.jsonc
c
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "my-pages-app",
"pages_build_output_dir": "./dist",
"compatibility_date": "2025-01-01",
"compatibility_flags": ["nodejs_compat"],
"vars": { "API_URL": "https://api.example.com" },
"kv_namespaces": [{ "binding": "KV", "id": "abc123" }],
"d1_databases": [{ "binding": "DB", "database_name": "prod-db", "database_id": "xyz789" }],
"r2_buckets": [{ "binding": "BUCKET", "bucket_name": "my-bucket" }],
"durable_objects": { "bindings": [{ "name": "COUNTER", "class_name": "Counter", "script_name": "counter-worker" }] },
"services": [{ "binding": "AUTH", "service": "auth-worker" }],
"ai": { "binding": "AI" },
"vectorize": [{ "binding": "VECTORIZE", "index_name": "my-index" }],
"analytics_engine_datasets": [{ "binding": "ANALYTICS" }]
}
## 环境覆盖
顶层 → 本地开发, `env.preview` → 预览, `env.production` → 生产
c
{
"vars": { "API_URL": "http://localhost:8787" },
"env": {
"production": { "vars": { "API_URL": "https://api.example.com" } }
}
}
**注意:** 如果覆盖 `vars`, `kv_namespaces`, `d1_databases` 等,必须全部重新定义 (不可继承)
## 本地密钥 (.dev.vars)
**仅限本地开发** - 不会部署:
bash
# .dev.vars (添加到 .gitignore)
SECRET_KEY="my-secret-value"
通过 `ctx.env.SECRET_KEY` 访问。设置生产环境密钥:
bash
echo "value" | npx wrangler pages secret put SECRET_KEY --project-name=my-app
## 静态配置文件
**_routes.json** - 自定义路由:
{ "version": 1, "include": ["/api/*"], "exclude": ["/static/*"] }
**_headers** - 静态响应头:
/static/*
Cache-Control: public, max-age=31536000
**_redirects** - 重定向:
/old /new 301
## 本地开发与部署
bas