cloudflare-worker-base
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudflare Worker Base Stack
Cloudflare Worker Base Stack
Production-tested: cloudflare-worker-base-test (https://cloudflare-worker-base-test.webfonts.workers.dev)
Last Updated: 2026-01-20
Status: Production Ready ✅
Latest Versions: hono@4.11.3, @cloudflare/vite-plugin@1.17.1, vite@7.3.1, wrangler@4.54.0
Skill Version: 3.1.0
Recent Updates (2025-2026):
- Wrangler 4.55+: Auto-config for frameworks ()
wrangler deploy --x-autoconfig - Wrangler 4.45+: Auto-provisioning for R2, D1, KV bindings (enabled by default)
- Workers RPC: JavaScript-native RPC via class for service bindings
WorkerEntrypoint - March 2025: Wrangler v4 release (minimal breaking changes, v3 supported until Q1 2027)
- June 2025: Native Integrations removed from dashboard (CLI-based approach with wrangler secrets)
- 2025 Platform: Workers VPC Services, Durable Objects Data Studio, 64 env vars (5KB each), unlimited Cron Triggers per Worker, WebSocket 32 MiB messages, node:fs/Web File System APIs
- 2025 Static Assets: Gradual rollout asset mismatch issue, free tier 429 errors with run_worker_first, Vite plugin auto-detection
- Hono 4.11.x: Enhanced TypeScript RPC type inference, cloneRawRequest utility, JWT aud validation, auth middleware improvements
经过生产环境验证:cloudflare-worker-base-test(https://cloudflare-worker-base-test.webfonts.workers.dev)
最后更新时间:2026-01-20
状态:已就绪可用于生产环境 ✅
最新版本:hono@4.11.3, @cloudflare/vite-plugin@1.17.1, vite@7.3.1, wrangler@4.54.0
技能版本:3.1.0
近期更新(2025-2026):
- Wrangler 4.55+:框架自动配置()
wrangler deploy --x-autoconfig - Wrangler 4.45+:R2、D1、KV绑定自动预配置(默认启用)
- Workers RPC:通过类实现JavaScript原生RPC,用于服务绑定
WorkerEntrypoint - 2025年3月:Wrangler v4发布(破坏性变更极少,v3版本支持至2027年第一季度)
- 2025年6月:控制台移除原生集成(采用基于CLI的wrangler secrets方式)
- 2025平台特性:Workers VPC服务、Durable Objects数据工作室、64个环境变量(每个5KB)、每个Worker支持无限Cron触发器、WebSocket 32 MiB消息、node:fs/Web文件系统API
- 2025静态资源:逐步推出资产不匹配问题修复、免费层使用run_worker_first时的429错误、Vite插件自动检测
- Hono 4.11.x:增强TypeScript RPC类型推断、cloneRawRequest工具、JWT aud校验、认证中间件优化
Quick Start (5 Minutes)
快速开始(5分钟)
bash
undefinedbash
undefined1. Scaffold project
1. 初始化项目
npm create cloudflare@latest my-worker -- --type hello-world --ts --git --deploy false --framework none
npm create cloudflare@latest my-worker -- --type hello-world --ts --git --deploy false --framework none
2. Install dependencies
2. 安装依赖
cd my-worker
npm install hono@4.11.3
npm install -D @cloudflare/vite-plugin@1.17.1 vite@7.3.1
cd my-worker
npm install hono@4.11.3
npm install -D @cloudflare/vite-plugin@1.17.1 vite@7.3.1
3. Create wrangler.jsonc
3. 创建wrangler.jsonc
{
"name": "my-worker",
"main": "src/index.ts",
"account_id": "YOUR_ACCOUNT_ID",
"compatibility_date": "2025-11-11",
"assets": {
"directory": "./public/",
"binding": "ASSETS",
"not_found_handling": "single-page-application",
"run_worker_first": ["/api/*"] // CRITICAL: Prevents SPA fallback from intercepting API routes
}
}
{
"name": "my-worker",
"main": "src/index.ts",
"account_id": "YOUR_ACCOUNT_ID",
"compatibility_date": "2025-11-11",
"assets": {
"directory": "./public/",
"binding": "ASSETS",
"not_found_handling": "single-page-application",
"run_worker_first": ["/api/*"] // 关键配置:防止SPA回退拦截API路由
}
}
4. Create vite.config.ts
4. 创建vite.config.ts
import { defineConfig } from 'vite'
import { cloudflare } from '@cloudflare/vite-plugin'
export default defineConfig({ plugins: [cloudflare()] })
import { defineConfig } from 'vite'
import { cloudflare } from '@cloudflare/vite-plugin'
export default defineConfig({ plugins: [cloudflare()] })
5. Create src/index.ts
5. 创建src/index.ts
import { Hono } from 'hono'
type Bindings = { ASSETS: Fetcher }
const app = new Hono<{ Bindings: Bindings }>()
app.get('/api/hello', (c) => c.json({ message: 'Hello!' }))
app.all('*', (c) => c.env.ASSETS.fetch(c.req.raw))
export default app // CRITICAL: Use this pattern (NOT { fetch: app.fetch })
import { Hono } from 'hono'
type Bindings = { ASSETS: Fetcher }
const app = new Hono<{ Bindings: Bindings }>()
app.get('/api/hello', (c) => c.json({ message: 'Hello!' }))
app.all('*', (c) => c.env.ASSETS.fetch(c.req.raw))
export default app // 关键配置:使用该模式(不要用{ fetch: app.fetch })
6. Deploy
6. 部署
npm run dev # Local: http://localhost:8787
wrangler deploy # Production
**Critical Configuration**:
- `run_worker_first: ["/api/*"]` - Without this, SPA fallback intercepts API routes returning `index.html` instead of JSON ([workers-sdk #8879](https://github.com/cloudflare/workers-sdk/issues/8879))
- `export default app` - Using `{ fetch: app.fetch }` causes "Cannot read properties of undefined" ([honojs/hono #3955](https://github.com/honojs/hono/issues/3955))npm run dev # 本地开发:http://localhost:8787
wrangler deploy # 生产环境部署
**关键配置**:
- `run_worker_first: ["/api/*"]` - 若无此配置,SPA回退会拦截API路由,返回`index.html`而非JSON(来源:[workers-sdk #8879](https://github.com/cloudflare/workers-sdk/issues/8879))
- `export default app` - 使用`{ fetch: app.fetch }`会导致“Cannot read properties of undefined”错误(来源:[honojs/hono #3955](https://github.com/honojs/hono/issues/3955))Known Issues Prevention
已知问题预防
This skill prevents 10 documented issues:
本技能可预防10类已记录的问题:
Issue #1: Export Syntax Error
问题1:导出语法错误
Error: "Cannot read properties of undefined (reading 'map')"
Source: honojs/hono #3955
Prevention: Use (NOT )
export default app{ fetch: app.fetch }错误信息:"Cannot read properties of undefined (reading 'map')"
来源:honojs/hono #3955
预防方案:使用(不要用)
export default app{ fetch: app.fetch }Issue #2: Static Assets Routing Conflicts
问题2:静态资源路由冲突
Error: API routes return instead of JSON
Source: workers-sdk #8879
Prevention: Add to wrangler.jsonc
index.html"run_worker_first": ["/api/*"]错误信息:API路由返回而非JSON
来源:workers-sdk #8879
预防方案:在wrangler.jsonc中添加
index.html"run_worker_first": ["/api/*"]Issue #3: Scheduled/Cron Not Exported
问题3:定时任务/Cron未导出
Error: "Handler does not export a scheduled() function"
Source: honojs/vite-plugins #275
Prevention: Use Module Worker format when needed:
typescript
export default {
fetch: app.fetch,
scheduled: async (event, env, ctx) => { /* ... */ }
}错误信息:"Handler does not export a scheduled() function"
来源:honojs/vite-plugins #275
预防方案:需要时使用Module Worker格式:
typescript
export default {
fetch: app.fetch,
scheduled: async (event, env, ctx) => { /* ... */ }
}Issue #4: HMR Race Condition
问题4:HMR竞争条件
Error: "A hanging Promise was canceled" during development
Source: workers-sdk #9518
Prevention: Use or later
@cloudflare/vite-plugin@1.13.13错误信息:开发期间出现"A hanging Promise was canceled"
来源:workers-sdk #9518
预防方案:使用或更高版本
@cloudflare/vite-plugin@1.13.13Issue #5: Static Assets Upload Race
问题5:静态资源上传竞争
Error: Non-deterministic deployment failures in CI/CD
Source: workers-sdk #7555
Prevention: Use Wrangler 4.x+ with retry logic (fixed in recent versions)
错误信息:CI/CD中出现非确定性部署失败
来源:workers-sdk #7555
预防方案:使用带重试逻辑的Wrangler 4.x+(最新版本已修复)
Issue #6: Service Worker Format Confusion
问题6:Service Worker格式混淆
Error: Using deprecated Service Worker format
Source: Cloudflare migration guide
Prevention: Always use ES Module format
错误信息:使用已弃用的Service Worker格式
来源:Cloudflare迁移指南
预防方案:始终使用ES Module格式
Issue #7: Gradual Rollouts Asset Mismatch (2025)
问题7:2025年逐步发布的资产不匹配问题
Error: 404 errors for fingerprinted assets during gradual deployments
Source: Cloudflare Static Assets Docs
Why It Happens: Modern frameworks (React/Vue/Angular with Vite) generate fingerprinted filenames (e.g., ). During gradual rollouts between versions, a user's initial request may go to Version A (HTML references ), but subsequent asset requests route to Version B (only has ), causing 404s
Prevention:
index-a1b2c3d4.jsindex-a1b2c3d4.jsindex-m3n4o5p6.js- Avoid gradual deployments with fingerprinted assets
- Use instant cutover deployments for static sites
- Or implement version-aware routing with custom logic
错误信息:逐步部署期间,带指纹的资产出现404错误
来源:Cloudflare Static Assets Docs
问题原因:现代框架(使用Vite的React/Vue/Angular)会生成带指纹的文件名(例如)。在版本间逐步部署时,用户的初始请求可能指向版本A(HTML引用),但后续资产请求会路由到版本B(仅包含),导致404错误
预防方案:
index-a1b2c3d4.jsindex-a1b2c3d4.jsindex-m3n4o5p6.js- 对带指纹的资产避免使用逐步部署
- 静态站点使用即时切换部署
- 或通过自定义逻辑实现版本感知路由
Issue #8: Free Tier 429 Errors with run_worker_first (2025)
问题8:2025年免费层使用run_worker_first时的429错误
Error: 429 (Too Many Requests) responses on asset requests when exceeding free tier limits
Source: Cloudflare Static Assets Billing Docs
Why It Happens: When using , requests matching specified patterns ALWAYS invoke your Worker script (counted toward free tier limits). After exceeding limits, these requests receive 429 instead of falling back to free static asset serving
Prevention:
run_worker_first- Upgrade to Workers Paid plan ($5/month) for unlimited requests
- Use negative patterns () to exclude paths from Worker invocation
!/pattern - Minimize patterns to only essential API routes
run_worker_first
错误信息:超过免费层限制后,资产请求返回429(请求过多)
来源:Cloudflare Static Assets Billing Docs
问题原因:使用时,匹配指定规则的请求始终会调用Worker脚本(计入免费层限制)。超过限制后,这些请求会收到429错误,而非回退到免费静态资源服务
预防方案:
run_worker_first- 升级到Workers付费计划(每月5美元),享受无限请求
- 使用否定模式()排除不需要调用Worker的路径
!/pattern - 将规则仅限定在必要的API路由
run_worker_first
Issue #9: Vite 8 Breaks nodejs_compat with require()
问题9:Vite 8破坏nodejs_compat与require()的兼容性
Error:
Source: workers-sdk #11948
Affected Versions: Vite 8.x with @cloudflare/vite-plugin 1.21.0+
Why It Happens: Vite 8 uses Rolldown bundler which doesn't convert to for external modules. Workers don't expose function, causing Node built-in module imports to fail at runtime.
Prevention:
Calling require for "buffer" in an environment that doesn't expose the require functionrequire()importrequire()typescript
// vite.config.ts - Add esmExternalRequirePlugin
import { defineConfig } from 'vite'
import { cloudflare } from '@cloudflare/vite-plugin'
import { esmExternalRequirePlugin } from 'vite'
import { builtinModules } from 'node:module'
export default defineConfig({
plugins: [
cloudflare(),
esmExternalRequirePlugin({
external: [/^node:/, ...builtinModules],
}),
],
})Status: Workaround available. Vite team working on fix (vitejs/vite#21452).
错误信息:
来源:workers-sdk #11948
受影响版本:Vite 8.x搭配@cloudflare/vite-plugin 1.21.0+
问题原因:Vite 8使用Rolldown打包器,不会将外部模块的转换为。Workers不暴露函数,导致Node内置模块导入在运行时失败
预防方案:
Calling require for "buffer" in an environment that doesn't expose the require functionrequire()importrequire()typescript
// vite.config.ts - 添加esmExternalRequirePlugin
import { defineConfig } from 'vite'
import { cloudflare } from '@cloudflare/vite-plugin'
import { esmExternalRequirePlugin } from 'vite'
import { builtinModules } from 'node:module'
export default defineConfig({
plugins: [
cloudflare(),
esmExternalRequirePlugin({
external: [/^node:/, ...builtinModules],
}),
],
})状态:已有临时解决方案。Vite团队正在修复(vitejs/vite#21452)
Issue #10: Vite base Option Breaks SPA Routing (1.13.8+)
问题10:Vite base选项破坏SPA路由(1.13.8+)
Error: returns 404 instead of index.html
Source: workers-sdk #11857
Affected Versions: @cloudflare/vite-plugin 1.13.8+
Why It Happens: Plugin now passes full URL with base path to Asset Worker (matching prod behavior). Platform support for not yet available.
Prevention (dev-mode workaround):
curl http://localhost:5173/prefixassets.basetypescript
// worker.ts - Strip base path in development
if (import.meta.env.DEV) {
url.pathname = url.pathname.replace(import.meta.env.BASE_URL, '');
if (url.pathname === '/') {
return this.env.ASSETS.fetch(request);
}
request = new Request(url, request);
}Status: Intentional change to align dev with prod. Platform feature planned for Q1 2026 (workers-sdk #9885).
assets.base错误信息:返回404而非index.html
来源:workers-sdk #11857
受影响版本:@cloudflare/vite-plugin 1.13.8+
问题原因:插件现在会将包含base路径的完整URL传递给Asset Worker(与生产环境行为一致)。但平台尚未支持特性
预防方案(开发模式临时解决):
curl http://localhost:5173/prefixassets.basetypescript
// worker.ts - 开发环境中移除base路径
if (import.meta.env.DEV) {
url.pathname = url.pathname.replace(import.meta.env.BASE_URL, '');
if (url.pathname === '/') {
return this.env.ASSETS.fetch(request);
}
request = new Request(url, request);
}状态:为对齐开发与生产环境的有意变更。平台特性计划于2026年第一季度推出(workers-sdk #9885)
assets.baseRoute Priority with run_worker_first
run_worker_first的路由优先级
Critical Understanding: returns for unknown routes (enables React Router, Vue Router). Without , this intercepts API routes!
"not_found_handling": "single-page-application"index.htmlrun_worker_firstRequest Routing with :
run_worker_first: ["/api/*"]- → Worker handles (returns JSON)
/api/hello - → Static Assets serve
/index.html - → Static Assets serve
/styles.cssstyles.css - → Static Assets serve
/unknown(SPA fallback)index.html
Static Assets Caching: Automatic edge caching. Cache bust with query strings:
<link href="/styles.css?v=1.0.0">Free Tier Warning (2025): patterns count toward free tier limits. After exceeding, requests get 429 instead of falling back to free static assets. Use negative patterns () or upgrade to Paid plan.
run_worker_first!/pattern关键理解:会为未知路由返回(支持React Router、Vue Router)。若无配置,该规则会拦截API路由!
"not_found_handling": "single-page-application"index.htmlrun_worker_first配置后的请求路由逻辑:
run_worker_first: ["/api/*"]- → 由Worker处理(返回JSON)
/api/hello - → 静态资源服务返回
/index.html - → 静态资源服务返回
/styles.cssstyles.css - → 静态资源服务返回
/unknown(SPA回退)index.html
静态资源缓存:自动边缘缓存。通过查询字符串实现缓存刷新:
<link href="/styles.css?v=1.0.0">2025免费层警告:规则会计入免费层限制。超过限制后,请求会收到429错误,而非回退到免费静态资源服务。可使用否定模式()或升级到付费计划。
run_worker_first!/patternAuto-Provisioning (Wrangler 4.45+)
自动资源配置(Wrangler 4.45+)
Default Behavior: Wrangler automatically provisions R2 buckets, D1 databases, and KV namespaces when deploying. This eliminates manual resource creation steps.
Critical: Always Specify Resource Names
⚠️ Edge Case (workers-sdk #11870): If you provide only without /, Wrangler uses the binding name as the resource name. This causes confusing behavior with and subcommands, which prefer → → .
bindingdatabase_namebucket_namewrangler devdatabase_iddatabase_namebindingjsonc
// ❌ DON'T: Binding-only creates database named "DB"
{
"d1_databases": [{ "binding": "DB" }]
}
// ✅ DO: Explicit names prevent confusion
{
"d1_databases": [
{
"binding": "DB",
"database_name": "my-app-db" // Always specify!
}
],
"r2_buckets": [
{
"binding": "STORAGE",
"bucket_name": "my-app-files" // Always specify!
}
],
"kv_namespaces": [
{
"binding": "CACHE",
"title": "my-app-cache" // Always specify!
}
]
}bash
undefined默认行为:Wrangler在部署时会自动预配置R2存储桶、D1数据库和KV命名空间。这省去了手动创建资源的步骤。
关键注意事项:始终指定资源名称
⚠️ 边缘情况(来源:workers-sdk #11870):若仅提供而未指定/,Wrangler会将绑定名称作为资源名称。这会导致和子命令出现混淆行为,因为它们优先使用 → → 。
bindingdatabase_namebucket_namewrangler devdatabase_iddatabase_namebindingjsonc
// ❌ 错误做法:仅指定绑定会创建名为"DB"的数据库
{
"d1_databases": [{ "binding": "DB" }]
}
// ✅ 正确做法:显式指定名称避免混淆
{
"d1_databases": [
{
"binding": "DB",
"database_name": "my-app-db" // 务必指定!
}
],
"r2_buckets": [
{
"binding": "STORAGE",
"bucket_name": "my-app-files" // 务必指定!
}
],
"kv_namespaces": [
{
"binding": "CACHE",
"title": "my-app-cache" // 务必指定!
}
]
}bash
undefinedDeploy - resources auto-provisioned if they don't exist
部署 - 若资源不存在则自动预配置
wrangler deploy
wrangler deploy
Disable auto-provisioning (use existing resources only)
禁用自动预配置(仅使用现有资源)
wrangler deploy --no-x-provision
**Benefits**:
- No separate `wrangler d1 create` / `wrangler r2 create` steps needed
- Idempotent - existing resources are used, not recreated
- Works with local dev (`wrangler dev` creates local emulated resources)wrangler deploy --no-x-provision
**优势**:
- 无需单独执行`wrangler d1 create` / `wrangler r2 create`步骤
- 幂等性:使用现有资源,不会重复创建
- 支持本地开发(`wrangler dev`会创建本地模拟资源)Workers RPC (Service Bindings)
Workers RPC(服务绑定)
What It Is: JavaScript-native RPC system for calling methods between Workers. Uses Cap'n Proto under the hood for zero-copy message passing.
Use Case: Split your application into multiple Workers (e.g., API Worker + Auth Worker + Email Worker) that call each other with type-safe methods.
Defining an RPC Service:
typescript
import { WorkerEntrypoint } from 'cloudflare:workers'
export class AuthService extends WorkerEntrypoint<Env> {
async verifyToken(token: string): Promise<{ userId: string; valid: boolean }> {
// Access bindings via this.env
const session = await this.env.SESSIONS.get(token)
return session ? { userId: session.userId, valid: true } : { userId: '', valid: false }
}
async createSession(userId: string): Promise<string> {
const token = crypto.randomUUID()
await this.env.SESSIONS.put(token, JSON.stringify({ userId }), { expirationTtl: 3600 })
return token
}
}
// Default export still handles HTTP requests
export default { fetch: ... }Calling from Another Worker:
typescript
// wrangler.jsonc
{
"services": [
{ "binding": "AUTH", "service": "auth-worker", "entrypoint": "AuthService" }
]
}
// In your main Worker
const { valid, userId } = await env.AUTH.verifyToken(authHeader)Key Points:
- Zero latency: Workers on same account typically run in same thread
- Type-safe: Full TypeScript support for method signatures
- 32 MiB limit: Max serialized RPC message size
- Self-bindings: In , shows as
wrangler devfor same-Worker calls[connected]
定义:用于Worker间调用方法的JavaScript原生RPC系统。底层使用Cap'n Proto实现零拷贝消息传递。
适用场景:将应用拆分为多个Worker(例如API Worker + 认证Worker + 邮件Worker),通过类型安全的方法相互调用。
定义RPC服务:
typescript
import { WorkerEntrypoint } from 'cloudflare:workers'
export class AuthService extends WorkerEntrypoint<Env> {
async verifyToken(token: string): Promise<{ userId: string; valid: boolean }> {
// 通过this.env访问绑定资源
const session = await this.env.SESSIONS.get(token)
return session ? { userId: session.userId, valid: true } : { userId: '', valid: false }
}
async createSession(userId: string): Promise<string> {
const token = crypto.randomUUID()
await this.env.SESSIONS.put(token, JSON.stringify({ userId }), { expirationTtl: 3600 })
return token
}
}
// 默认导出仍处理HTTP请求
export default { fetch: ... }从其他Worker调用:
typescript
// wrangler.jsonc
{
"services": [
{ "binding": "AUTH", "service": "auth-worker", "entrypoint": "AuthService" }
]
}
// 在主Worker中调用
const { valid, userId } = await env.AUTH.verifyToken(authHeader)关键点:
- 零延迟:同一账户下的Worker通常在同一线程运行
- 类型安全:方法签名完全支持TypeScript
- 32 MiB限制:RPC消息序列化后的最大大小
- 自绑定:在中,同一Worker内的调用显示为
wrangler dev[connected]
Troubleshooting
故障排查
Random "Response Already Sent" Errors in Development
开发环境中随机出现的“Response Already Sent”错误
Symptom: Sporadic during
Source: workers-sdk #11932
Cause: Cache corruption in directory or stale Vite cache
ResponseSentError: The response has already been sent to the browser and cannot be alteredwrangler dev.wranglerSolution:
bash
undefined症状:期间偶尔出现
来源:workers-sdk #11932
原因:目录中的缓存损坏或Vite缓存过期
wrangler devResponseSentError: The response has already been sent to the browser and cannot be altered.wrangler解决方案:
bash
undefinedClear all caches
清除所有缓存
rm -rf .wrangler dist node_modules/.vite
rm -rf .wrangler dist node_modules/.vite
Rebuild
重新构建
npm run build
npm run build
Recreate local D1 databases if needed
若需要,重新创建本地D1数据库
wrangler d1 execute DB --local --file schema.sql
**Applies to**: Wrangler 4.x full Workers mode (not Cloudflare Pages)wrangler d1 execute DB --local --file schema.sql
**适用范围**:Wrangler 4.x全Worker模式(非Cloudflare Pages)Community Tips
社区小贴士
Note: These tips come from community discussions. Verify against your version.
注意:这些小贴士来自社区讨论,请根据你的版本进行验证。
Avoid vite-tsconfig-paths v6 with React SSR
React SSR场景下避免使用vite-tsconfig-paths v6
Source: workers-sdk #11825 (Community-sourced)
If using React SSR with , pin to :
@cloudflare/vite-pluginvite-tsconfig-paths@5.1.4bash
npm install vite-tsconfig-paths@5.1.4Why: Version 6.x doesn't follow path aliases during dependency scan, causing duplicate React instances and "Invalid hook call" errors.
Applies to: Projects using TypeScript path aliases with React SSR
来源:workers-sdk #11825(社区贡献)
若在使用的同时使用React SSR,请固定版本为:
@cloudflare/vite-pluginvite-tsconfig-paths@5.1.4bash
npm install vite-tsconfig-paths@5.1.4原因:6.x版本在依赖扫描期间不遵循路径别名,导致React实例重复,出现“Invalid hook call”错误。
适用范围:使用TypeScript路径别名的React SSR项目
Use crypto.randomUUID() Instead of uuid Package
使用crypto.randomUUID()替代uuid包
Source: workers-sdk #11957
The package (ESM) can cause runtime crashes with "fileURLToPath undefined" in Workers. Use the native Web Crypto API instead:
uuid@11typescript
// ✅ Native Workers API (recommended)
const uuid = crypto.randomUUID();
// ❌ Avoid uuid package in Workers
import { v4 as uuidv4 } from 'uuid'; // May crashApplies to: All Workers projects needing UUIDs
uuid@11typescript
// ✅ 推荐使用Workers原生API
const uuid = crypto.randomUUID();
// ❌ 在Workers中避免使用uuid包
import { v4 as uuidv4 } from 'uuid'; // 可能会崩溃适用范围:所有需要生成UUID的Workers项目
Commands
命令
/deploy
- One-Command Deploy Pipeline
/deploy/deploy
- 一键部署流水线
/deployUse when: Ready to commit, push, and deploy your Cloudflare Worker in one step.
Does:
- Pre-flight: Verifies wrangler config, checks for changes, builds, runs TypeScript check
- Commit & Push: Stages changes, generates conventional commit message, pushes to remote
- Deploy: Runs , captures Worker URL
wrangler deploy - Report: Shows commit hash, branch, deployed URL, any warnings
Time savings: 2-3 min per deploy cycle
Edge Cases Handled:
- No changes to commit → skips to deploy
- Build script missing → warns and continues
- No remote configured → reports error with suggestion
- TypeScript errors → stops and reports
适用场景:准备好提交、推送并部署Cloudflare Worker时使用。
执行步骤:
- 预检查:验证wrangler配置、检查变更、构建项目、运行TypeScript校验
- 提交并推送:暂存变更、生成规范的提交信息、推送到远程仓库
- 部署:执行,获取Worker URL
wrangler deploy - 报告:显示提交哈希、分支、部署URL及任何警告
时间节省:每次部署周期节省2-3分钟
处理的边缘情况:
- 无变更需要提交 → 直接跳至部署步骤
- 缺少构建脚本 → 发出警告并继续
- 未配置远程仓库 → 报告错误并给出建议
- TypeScript错误 → 终止流程并报告
Bundled Resources
配套资源
Templates: Complete setup files in directory (wrangler.jsonc, vite.config.ts, package.json, tsconfig.json, src/index.ts, public/index.html, styles.css, script.js)
templates/模板:目录下包含完整的配置文件(wrangler.jsonc、vite.config.ts、package.json、tsconfig.json、src/index.ts、public/index.html、styles.css、script.js)
templates/Official Documentation
官方文档
- Cloudflare Workers: https://developers.cloudflare.com/workers/
- Static Assets: https://developers.cloudflare.com/workers/static-assets/
- Vite Plugin: https://developers.cloudflare.com/workers/vite-plugin/
- Wrangler: https://developers.cloudflare.com/workers/wrangler/
- Hono: https://hono.dev/docs/getting-started/cloudflare-workers
- MCP Tool: Use for latest docs
mcp__cloudflare-docs__search_cloudflare_documentation
- Cloudflare Workers:https://developers.cloudflare.com/workers/
- Static Assets:https://developers.cloudflare.com/workers/static-assets/
- Vite Plugin:https://developers.cloudflare.com/workers/vite-plugin/
- Wrangler:https://developers.cloudflare.com/workers/wrangler/
- Hono:https://hono.dev/docs/getting-started/cloudflare-workers
- MCP工具:使用获取最新文档
mcp__cloudflare-docs__search_cloudflare_documentation
Dependencies (Latest Verified 2026-01-03)
依赖项(最近验证于2026-01-03)
json
{
"dependencies": {
"hono": "^4.11.3"
},
"devDependencies": {
"@cloudflare/vite-plugin": "^1.17.1",
"@cloudflare/workers-types": "^4.20260103.0",
"vite": "^7.3.1",
"wrangler": "^4.54.0",
"typescript": "^5.9.3"
}
}json
{
"dependencies": {
"hono": "^4.11.3"
},
"devDependencies": {
"@cloudflare/vite-plugin": "^1.17.1",
"@cloudflare/workers-types": "^4.20260103.0",
"vite": "^7.3.1",
"wrangler": "^4.54.0",
"typescript": "^5.9.3"
}
}Production Validation
生产环境验证
Live Example: https://cloudflare-worker-base-test.webfonts.workers.dev (build time: 45 min, 0 errors, all 10 issues prevented)
Last verified: 2026-01-20 | Skill version: 3.1.0 | Changes: Added Vite 8 nodejs_compat workaround (Issue #9), Vite base option regression (Issue #10), auto-provisioning edge case warning, troubleshooting section for cache corruption, and community tips for vite-tsconfig-paths v6 and uuid package alternatives. Research conducted by skill-researcher agent covering post-May 2025 Workers SDK updates.
最后验证时间:2026-01-20 | 技能版本:3.1.0 | 变更内容:新增Vite 8 nodejs_compat临时解决方案(问题9)、Vite base选项回退问题(问题10)、自动预配置边缘情况警告、缓存损坏故障排查章节,以及vite-tsconfig-paths v6和uuid包替代方案的社区小贴士。由技能研究Agent基于2025年5月之后的Workers SDK更新进行调研。