必须全局安装 firebase-tools 并确保 vscode 终端能识别,否则无法启动模拟器;需配置 launch.json 以 attach 模式连接 functions emulator 的 node 进程,并等待模拟器就绪后再调试。

firebase-tools 必须全局安装且 VSCode 终端能识别
VSCode 本身不运行 Firebase 模拟器,全靠 firebase-tools CLI 启动;如果终端里敲 firebase emulators:start 报 command not found,后续所有调试都无从谈起。
常见错误现象:系统终端(如 macOS Terminal 或 Windows PowerShell)能正常执行 firebase --version,但 VSCode 内置终端报错。
- 在 VSCode 终端中运行
firebase --version,确认输出类似13.24.0 - 若未安装,执行
npm install -g firebase-tools(别加--save-dev,全局才有效) - 若已安装但 VSCode 终端不识别,检查设置中
terminal.integrated.inheritEnv是否为true;改完必须重启 VSCode - 首次使用前必须运行
firebase login --interactive,否则模拟器启动时会卡在认证环节
启动 Emulator Suite 前先确认服务联动配置正确
模拟器不是“配好就能断点”,得先确保函数代码真能在本地跑起来、被事件触发——比如你写了 onDocumentCreated,就得有 Firestore Emulator 配合写入文档才能触发它。
使用场景:你修改了 functions/index.ts,想边改边看日志、打断点,而不是每次 firebase deploy。
- 确保项目已执行过
firebase init functions和firebase init firestore(或其他需联动的服务) -
firebase emulators:start启动后,注意终端输出的端口:Functions默认是http://localhost:5001,UI 是http://localhost:4000 - 在 UI 的 “Functions” 标签页里点击函数名可直接触发 HTTP 函数;或用
curl "http://localhost:5001/{project-id}/{region}/helloWorld"手动调用 - 若函数没日志输出,检查
firebase.json中emulators.functions.port是否被其他进程占用
launch.json 必须用 attach 模式连接 Functions Emulator 的 Node 进程
VSCode 默认不连接 Functions Emulator 的 Node 进程,必须手动指定调试入口——不是调试你的 index.ts 文件,而是让 VSCode attach 到 emulator 启动的 Node 子进程上。
关键点:Functions Emulator 会自动启用 --inspect,但只监听 127.0.0.1:9229(旧版)或动态端口(新版),不能直接 launch,得用 attach 模式。
- 在项目根目录创建
.vscode/launch.json,内容为:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach to Firebase Functions",
"port": 9229,
"address": "127.0.0.1",
"localRoot": "${workspaceFolder}/functions",
"remoteRoot": "/workspace/functions",
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/functions/lib/**/*.js"]
}
]
}
- 启动模拟器前,先在 VSCode 中按
Ctrl+Shift+D打开调试面板,选中该配置,再点绿色 ▶ 启动 attach - 新版
firebase-tools(v12+)可能使用动态调试端口,此时需在firebase.json中显式固定:"functions": { "port": 5001, "inspectFunctions": true } - 断点只能打在编译后的
.js文件上(即lib/下),或确保sourceMaps和outFiles路径匹配 TS 编译输出
调试时容易忽略的类型与路径陷阱
断点打了没反应、变量显示 undefined、firestore.collection() 没智能提示——这些问题往往和类型定义、TS 编译路径或环境隔离有关,而非调试配置本身。
- 确保已安装
@types/firebase(前端)或@types/firebase-admin(函数端),二者不可混用 - 检查
tsconfig.json中"types"是否包含"firebase"或"firebase-admin",或确认"typeRoots"包含"node_modules/@types" - 函数代码在
functions/子目录下,launch.json中的localRoot和outFiles必须指向该子目录下的构建产物(如functions/lib),不是项目根目录 - 若用
pnpm或nvm管理 Node 版本,firebase-tools安装时务必用同一环境执行npm install -g firebase-tools,否则 CLI 可能找不到全局模块
最常被跳过的一步:启动 firebase emulators:start 后,必须等控制台明确输出 ✔ Functions Emulator started at http://localhost:5001 并看到 ✔ All emulators ready!,再启动 VSCode 的 attach 调试;早于这个时机 attach,会连不上进程。











