You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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转义问题:

  1. 在项目根目录创建test-firestore.sh文件:
#!/bin/bash
npm run test-once
  1. 给脚本添加执行权限:
chmod +x test-firestore.sh
  1. 修改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\""
}

验证步骤

  1. 先单独执行npm run test-once,确认Vitest能正常运行
  2. 执行npm run test-rules,检查Firebase模拟器是否正常启动,且Vitest测试能顺利完成

内容的提问来源于stack exchange,提问作者tristansokol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 19:37:16