firebase emulators:exec无法正常运行vitest测试问题求助
解决Firebase Emulators + Vitest ESM 兼容性问题
问题分析
你遇到的核心问题是:Firebase Emulators的emulators:exec命令在执行Vitest测试时,子进程的Node环境未正确识别项目的ESM配置(package.json中"type": "module"),导致尝试用CommonJS的require()加载Vitest的ESM模块,触发ERR_REQUIRE_ESM错误。之前出现的/bin/sh: 0: Illegal option --错误,则是JSON脚本中的引号转义冲突导致的。
解决方案
方案1:直接调用Vitest的ESM入口
修改package.json中的test-rules脚本,绕过npm脚本的间接调用,直接指定Vitest的ESM模块入口,强制Node以ESM模式加载:
"scripts": { "test-once": "vitest run", "test-rules": "firebase emulators:exec --only firestore \"node node_modules/vitest/vitest.mjs run\"" }
方案2:用bash脚本封装测试命令
通过独立脚本避免shell转义问题:
- 在项目根目录创建
test-firestore.sh文件:
#!/bin/bash npm run test-once
- 给脚本添加执行权限:
chmod +x test-firestore.sh
- 修改
package.json脚本:
"scripts": { "test-once": "vitest run", "test-rules": "firebase emulators:exec --only firestore \"./test-firestore.sh\"" }
方案3:强制Node使用ESM模式
通过设置NODE_OPTIONS环境变量,让子进程强制以ESM模式运行:
"scripts": { "test-once": "vitest run", "test-rules": "firebase emulators:exec --only firestore \"NODE_OPTIONS=--experimental-specifier-resolution=node npm run test-once\"" }
验证步骤
- 先单独执行
npm run test-once,确认Vitest能正常运行 - 执行
npm run test-rules,检查Firebase模拟器是否正常启动,且Vitest测试能顺利完成
内容的提问来源于stack exchange,提问作者tristansokol
相关产品推荐
相关产品推荐

