cloudflare-workers-dev-experience
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudflare Workers Developer Experience
Cloudflare Workers 开发者体验
Local development setup with Wrangler, Miniflare, and modern tooling.
使用 Wrangler、Miniflare 和现代工具搭建本地开发环境。
Quick Start
快速开始
bash
undefinedbash
undefinedCreate new project
创建新项目
bunx create-cloudflare@latest my-worker
bunx create-cloudflare@latest my-worker
Or from scratch
或从零开始
mkdir my-worker && cd my-worker
bun init -y
bun add -d wrangler @cloudflare/workers-types
mkdir my-worker && cd my-worker
bun init -y
bun add -d wrangler @cloudflare/workers-types
Start local development
启动本地开发
bunx wrangler dev
undefinedbunx wrangler dev
undefinedEssential wrangler.jsonc
必备 wrangler.jsonc 配置
jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2024-12-01",
// Development settings
"dev": {
"port": 8787,
"local_protocol": "http"
},
// Environment variables (non-secret)
"vars": {
"ENVIRONMENT": "development"
},
// Bindings
"kv_namespaces": [
{ "binding": "KV", "id": "abc123", "preview_id": "def456" }
],
"d1_databases": [
{ "binding": "DB", "database_id": "xyz789", "database_name": "my-db" }
],
"r2_buckets": [
{ "binding": "BUCKET", "bucket_name": "my-bucket" }
]
}jsonc
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2024-12-01",
// 开发设置
"dev": {
"port": 8787,
"local_protocol": "http"
},
// 环境变量(非机密)
"vars": {
"ENVIRONMENT": "development"
},
// 绑定配置
"kv_namespaces": [
{ "binding": "KV", "id": "abc123", "preview_id": "def456" }
],
"d1_databases": [
{ "binding": "DB", "database_id": "xyz789", "database_name": "my-db" }
],
"r2_buckets": [
{ "binding": "BUCKET", "bucket_name": "my-bucket" }
]
}Critical Rules
关键规则
- Always use for local testing - Simulates Cloudflare runtime accurately
wrangler dev - Set - Controls runtime behavior, update quarterly
compatibility_date - Use preview IDs for local dev - Separate from production bindings
- Configure TypeScript properly - Use
@cloudflare/workers-types - Enable source maps - Better error stacks in development
- 始终使用 进行本地测试 - 精准模拟 Cloudflare 运行时环境
wrangler dev - 设置 - 控制运行时行为,建议每季度更新一次
compatibility_date - 为本地开发使用预览 ID - 与生产环境绑定分离
- 正确配置 TypeScript - 使用
@cloudflare/workers-types - 启用源映射 - 开发阶段获得更清晰的错误堆栈
Top 6 Errors Prevented
可预防的六大常见错误
| Error | Symptom | Prevention |
|---|---|---|
| Module not found | Import errors on deploy | Set |
| Binding undefined | | Add |
| HMR not working | Changes not reflecting | Check port conflicts, use |
| D1 schema mismatch | Queries fail locally | Run migrations on local DB |
| Type errors | Missing binding types | Generate types with |
| CORS issues | Browser blocking requests | Add CORS headers in dev handler |
| 错误类型 | 症状表现 | 预防措施 |
|---|---|---|
| 模块未找到 | 部署时出现导入错误 | 在 tsconfig 中设置 |
| 绑定未定义 | 本地环境中 | 为 KV 命名空间配置添加 |
| HMR 失效 | 修改内容未实时同步 | 检查端口冲突,使用 |
| D1 架构不匹配 | 本地数据库查询失败 | 在本地数据库上运行迁移脚本 |
| 类型错误 | 缺少绑定类型定义 | 使用 |
| CORS 问题 | 浏览器拦截请求 | 在开发处理器中添加 CORS 头部 |
Local Development Workflow
本地开发工作流
bash
undefinedbash
undefinedStart dev server (recommended)
启动开发服务器(推荐)
bunx wrangler dev
bunx wrangler dev
With live reload
启用热重载
bunx wrangler dev --live-reload
bunx wrangler dev --live-reload
Remote mode (use actual Cloudflare services)
远程模式(使用真实 Cloudflare 服务)
bunx wrangler dev --remote
bunx wrangler dev --remote
Specify environment
指定环境
bunx wrangler dev --env staging
bunx wrangler dev --env staging
Custom port
自定义端口
bunx wrangler dev --port 3000
undefinedbunx wrangler dev --port 3000
undefinedTypeScript Configuration
TypeScript 配置
tsconfig.json:
json
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"types": ["@cloudflare/workers-types"],
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}tsconfig.json:
json
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"types": ["@cloudflare/workers-types"],
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}Package.json Scripts
Package.json 脚本
json
{
"scripts": {
"dev": "wrangler dev",
"deploy": "wrangler deploy",
"deploy:staging": "wrangler deploy --env staging",
"deploy:production": "wrangler deploy --env production",
"test": "vitest",
"test:watch": "vitest --watch",
"type-check": "tsc --noEmit",
"lint": "eslint src/",
"types": "wrangler types",
"tail": "wrangler tail",
"db:migrate": "wrangler d1 migrations apply DB",
"db:studio": "wrangler d1 execute DB --local --command 'SELECT 1'"
}
}json
{
"scripts": {
"dev": "wrangler dev",
"deploy": "wrangler deploy",
"deploy:staging": "wrangler deploy --env staging",
"deploy:production": "wrangler deploy --env production",
"test": "vitest",
"test:watch": "vitest --watch",
"type-check": "tsc --noEmit",
"lint": "eslint src/",
"types": "wrangler types",
"tail": "wrangler tail",
"db:migrate": "wrangler d1 migrations apply DB",
"db:studio": "wrangler d1 execute DB --local --command 'SELECT 1'"
}
}Debugging
调试指南
Console Logging
控制台日志
typescript
// Development-only logging
export default {
async fetch(request: Request, env: Env): Promise<Response> {
if (env.ENVIRONMENT === 'development') {
console.log('Request:', request.method, request.url);
console.log('Headers:', Object.fromEntries(request.headers));
}
// Handler logic...
}
};typescript
// 仅开发环境日志
export default {
async fetch(request: Request, env: Env): Promise<Response> {
if (env.ENVIRONMENT === 'development') {
console.log('Request:', request.method, request.url);
console.log('Headers:', Object.fromEntries(request.headers));
}
// 处理器逻辑...
}
};Using wrangler tail
使用 wrangler tail
bash
undefinedbash
undefinedReal-time logs from deployed worker
已部署 Worker 的实时日志
wrangler tail
wrangler tail
Filter by status
按状态过滤
wrangler tail --status error
wrangler tail --status error
Filter by method
按请求方法过滤
wrangler tail --method POST
wrangler tail --method POST
JSON format for parsing
JSON 格式输出以便解析
wrangler tail --format json
undefinedwrangler tail --format json
undefinedVS Code Debugging
VS Code 调试
.vscode/launch.json:
json
{
"version": "0.2.0",
"configurations": [
{
"name": "Wrangler Dev",
"type": "node",
"request": "launch",
"runtimeExecutable": "bunx",
"runtimeArgs": ["wrangler", "dev", "--inspector-port", "9229"],
"skipFiles": ["<node_internals>/**"],
"sourceMaps": true
}
]
}.vscode/launch.json:
json
{
"version": "0.2.0",
"configurations": [
{
"name": "Wrangler Dev",
"type": "node",
"request": "launch",
"runtimeExecutable": "bunx",
"runtimeArgs": ["wrangler", "dev", "--inspector-port", "9229"],
"skipFiles": ["<node_internals>/**"],
"sourceMaps": true
}
]
}When to Load References
参考资源加载时机
Load specific references based on the task:
- Setting up project? → Load for complete setup guide
references/local-development.md - Configuring wrangler? → Load for all configuration options
references/wrangler-config.md - Debugging issues? → Load for debugging techniques
references/debugging-tools.md
根据任务需求加载特定参考资源:
- 搭建项目? → 加载 获取完整搭建指南
references/local-development.md - 配置 Wrangler? → 加载 查看所有配置选项
references/wrangler-config.md - 调试问题? → 加载 学习调试技巧
references/debugging-tools.md
Templates
模板
| Template | Purpose | Use When |
|---|---|---|
| Complete wrangler config | Starting new project |
| Development utilities | Adding dev helpers |
| 模板 | 用途 | 使用场景 |
|---|---|---|
| 完整 Wrangler 配置模板 | 启动新项目时 |
| 开发工具集模板 | 添加开发辅助功能时 |
Scripts
脚本
| Script | Purpose | Command |
|---|---|---|
| Initialize dev environment | |
| 脚本 | 用途 | 命令 |
|---|---|---|
| 初始化开发环境 | |
Resources
相关资源
- Wrangler CLI: https://developers.cloudflare.com/workers/wrangler/
- Configuration: https://developers.cloudflare.com/workers/wrangler/configuration/
- Local Development: https://developers.cloudflare.com/workers/testing/local-development/