必须先确认 firebase-tools 已全局安装且 VSCode 终端可识别,运行 firebase --version 应输出版本号(如13.24.0);若报 command not found,需执行 npm install -g firebase-tools 并确保 terminal.integrated.inheritEnv 为 true,重启 VSCode 后再登录 firebase login --interactive。

确认 firebase-tools 已正确安装并可被 VSCode 终端识别
VSCode 本身不运行 Firebase 模拟器,全靠 firebase-tools CLI 启动;如果终端里敲 firebase emulators:start 报 command not found,后续所有调试都无从谈起。
常见错误现象:VSCode 内置终端报错,但系统终端(如 macOS Terminal 或 Windows PowerShell)能正常执行命令。
- 在终端中运行
firebase --version,确认输出类似13.24.0 - 若未安装,用
npm install -g firebase-tools(别加--save-dev,全局才有效) - 若已安装但 VSCode 终端不识别,检查设置中
terminal.integrated.inheritEnv是否设为true;改完重启 VSCode - 首次使用前必须运行
firebase login --interactive,否则模拟器启动时会卡在认证环节
初始化并启动 Emulator Suite,验证 Functions 能被本地触发
模拟器不是“配好就能断点”,得先确保函数代码真能在本地跑起来、被事件触发——比如你写了个 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调用,例如:curl "http://localhost:5001/{project-id}/{region}/helloWorld" - 若函数没日志输出,检查
firebase.json中emulators.functions的port是否被其他进程占用
在 VSCode 中配置 launch.json 实现 Node.js 断点调试
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 Functions Emulator",
"port": 9229,
"address": "127.0.0.1",
"localRoot": "${workspaceFolder}/functions",
"remoteRoot": "/workspace/functions",
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/functions/lib/**/*.js"]
}
]
}
- 启动模拟器前,先在 VSCode 中按
Ctrl+Shift+D打开调试面板,选中该配置,点击绿色 ▶️(此时不会立即连接,只是预备) - 再运行
firebase emulators:start;几秒后 VSCode 底部状态栏会显示 “Connected to port 9229” - 在
functions/index.ts中打断点,然后通过 UI 或 curl 触发函数,VSCode 就会停住 - 若提示 “Cannot connect”,说明 emulator 启用了新式动态 inspect 端口(v12+),此时改用
"port": 0并启用"autoAttachChildProcesses": true
处理环境变量与 TypeScript 源码映射问题
本地调试时,process.env.FIREBASE_CONFIG 是模拟器注入的,但如果你在函数里读取了自定义环境变量(比如 API_KEY),默认不会透传——而且 TS 编译后的 .js 文件路径和源码不一致,断点可能不生效。
- 把自定义变量写进
firebase.json的emulators.functions.environmentVariables字段,例如:"API_KEY": "dev-key" - 确保
tsconfig.json中"sourceMap": true和"outDir": "./lib"已启用,且functions/package.json的main指向lib/index.js - 不要在
functions目录下单独运行tsc,应由 Firebase CLI 在启动模拟器时自动编译(它会读tsconfig.json) - 若断点灰色不可用,检查 VSCode 左下角是否显示 “No debug adapter installed for TypeScript”——说明缺少
ms-vscode.vscode-typescript-next插件或版本太旧
outDir 或 rootDir 配错,断点就永远停不住。这两处出问题,比登录失败还难排查。


















