把博客搬上 Cloudflare Pages,构建直接挂了。

报错

npm run build 时日志里几个关键的错:

[error] [POST] http://localhost/__nuxt_content/content/query — Page not found
[error] [GET] http://localhost/api/__sitemap__/urls — Page not found
[error] [@nuxt/sitemap] Failed to fetch source
[error] [GET] "/sitemap.xml": 500 Server Error
Failed: build command exited with code: 1

原因

Cloudflare Pages 默认只服务静态文件。@nuxt/content v3 和 @nuxtjs/sitemap 都依赖 server runtime(/__nuxt_content/.../api/__sitemap__/urls 都是 server route),这些在默认环境跑不起来,全 404。

nuxt build 又会主动 prerender,模拟 http://localhost 跑一遍这些接口抓结果,所以 build 阶段就挂了。

解决

不要 prerender,让 Cloudflare 跑 server runtime。

nuxt.config.ts 改三处:

  • sitemap 删掉 sources: ['/api/__sitemap__/urls'],只留 autoLastmod: true
  • nitro.prerendercrawlLinks: falseroutes: []
  • build.transpile['@nuxt/content']

Cloudflare Pages 控制台要打开 nodejs_compat flag,不然 @nuxt/content 内部的 fs 之类会报缺 API。环境变量加一个 NITRO_PRESET=cloudflare-pages

验证

本地跑:

NITRO_PRESET=cloudflare-pages npm run build

产物在 .output/public(静态资源)和 .output/server(Workers 代码)。wrangler pages deploy .output/public 推到 Cloudflare,所有功能都在。

别走错的路

不要为了上 Cloudflare 降级到 nuxt generate 全静态部署。@nuxt/content v3 不支持纯静态,要么回退到 v2、要么放弃 v3 的 server query 功能——都不值得。

评论系统开发中,敬请期待