部署Next.js应用到Firebase时找不到生产构建目录的求助
我首次尝试将React+TypeScript开发的Next.js前端应用部署到Firebase,所有页面均为.tsx文件,入口为index.tsx,代码位于frontend目录。本地构建运行一切正常,但执行命令sudo firebase deploy --only hosting --project relu-backend时,Google Cloud日志报出错误:
Could not find a production build in the '/frontend/.next' directory
怀疑是functions目录index.js中的distDir配置问题,但多次尝试仍未解决。以下是项目相关文件信息:
项目文件结构
- 项目根目录
frontend/.next/pages/(含index.tsx及其他页面)package.jsontsconfig.json
functions/index.jspackage.json
firebase.json
firebase.json 内容
{ "hosting": { "public": "frontend/public", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "**", "function": "nextServer" } ] }, "functions": { "source": "functions" } }
frontend/package.json 内容
{ "name": "frontend", "version": "1.0.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start" }, "dependencies": { "next": "^13.4.0", "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "@types/react": "^18.2.0", "@types/react-dom": "^18.2.0", "typescript": "^5.0.4" } }
functions/package.json 内容
{ "name": "functions", "version": "1.0.0", "main": "index.js", "scripts": { "build": "tsc", "serve": "firebase emulators:start --only functions", "shell": "firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions" }, "dependencies": { "firebase-admin": "^11.9.0", "firebase-functions": "^4.4.1", "next": "^13.4.0", "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "typescript": "^5.0.4" }, "engines": { "node": "18" } }
functions/index.js 内容
const functions = require("firebase-functions"); const next = require("next"); const dev = process.env.NODE_ENV !== "production"; const app = next({ dev, distDir: "../frontend/.next" }); const handle = app.getRequestHandler(); exports.nextServer = functions.https.onRequest((req, res) => { return app.prepare().then(() => handle(req, res)); });
本地frontend/.next目录文件列表
.next/cache/server/static/build-idmanifest.jsonnext-env.d.tspackage.json
问题解决步骤
1. 确保部署前完成生产构建
进入frontend目录执行构建命令,生成完整的生产构建文件:
cd frontend npm run build
确认frontend/.next目录存在且包含上述文件列表中的内容。
2. 移除sudo执行部署命令
使用sudo会导致构建目录权限异常,Firebase CLI无法读取.next文件。改用普通用户权限执行:
firebase deploy --only hosting,functions --project relu-backend
注意需同时部署Hosting和Functions,因为Hosting的请求转发依赖Functions中的Next.js服务。
3. 修正firebase.json的忽略规则
确保Firebase部署时包含frontend/.next目录,在hosting.ignore中添加例外规则:
"ignore": [ "firebase.json", "**/.*", "**/node_modules/**", "!frontend/.next/**" ]
同时检查项目根目录和frontend目录的.gitignore,确保没有排除.next目录(若有则临时注释)。
4. 验证distDir路径正确性
当前functions/index.js中的distDir: "../frontend/.next"是正确的(基于functions目录相对根目录的位置),但需确保部署时该路径对应的目录确实存在于Firebase服务器上。
5. 对齐Node.js版本
确保本地Node.js版本与functions/package.json中engines.node指定的版本一致(如18.x),版本不一致可能导致构建或运行时错误。
6. 检查构建日志
重新执行npm run build时,查看终端输出是否有隐藏的构建错误,比如TypeScript语法错误、依赖缺失等,这些都可能导致.next目录生成不完整。
内容的提问来源于stack exchange,提问作者Dag Malstaf

