Next.js+TypeScript中使用firebase/auth的createUserWithEmailAndPassword时Jest报错
Next.js + TypeScript + Firebase Auth Jest 模块解析错误解决方案
核心问题
Jest 默认只转译项目源码,不处理 node_modules 中的 ES 模块,而 Firebase v9+ 采用纯 ES 模块分发,导致 Jest 无法解析其导出语法。
可行解决方案
1. 配置 Jest 转译 Firebase 相关包
修改 jest.config.js,调整 transformIgnorePatterns,让 Jest 转译 Firebase 及其子包:
module.exports = { testEnvironment: 'jsdom', preset: 'ts-jest', transform: { '^.+\\.(ts|tsx)$': 'ts-jest', }, // 允许转译 firebase 和 @firebase 开头的包 transformIgnorePatterns: ['node_modules/(?!(firebase|@firebase)/)'], // 可选:直接映射到 Firebase 的 CommonJS 构建版本 moduleNameMapper: { '^firebase/auth$': '<rootDir>/node_modules/firebase/auth/dist/index.cjs.js', }, };
2. 适配 TypeScript 配置(针对 ESM 冲突)
创建独立的 tsconfig.jest.json,覆盖主配置的模块格式,适配 Jest 的 CommonJS 需求:
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "CommonJS", "target": "ES6", "esModuleInterop": true }, "include": ["**/*.test.ts", "**/*.test.tsx"] }
然后在 jest.config.js 中指定该配置:
module.exports = { // ...其他配置 globals: { 'ts-jest': { tsconfig: './tsconfig.jest.json', }, }, };
3. 临时切换到 Firebase Compat 模式
如果上述配置仍不生效,可暂时使用 Firebase 的兼容层(兼容 CommonJS),修改导入语句:
// 替换原导入 import { createUserWithEmailAndPassword } from 'firebase/auth/compat';
4. 切换到 Babel 转译(终极方案)
若 ts-jest 适配困难,改用 Babel 处理转译:
- 安装依赖:
npm install --save-dev @babel/preset-env @babel/preset-typescript @babel/preset-react babel-jest
- 创建
babel.config.js:
module.exports = { presets: [ ['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript', '@babel/preset-react', ], };
- 修改
jest.config.js:
module.exports = { testEnvironment: 'jsdom', transform: { '^.+\\.(ts|tsx)$': 'babel-jest', }, transformIgnorePatterns: ['node_modules/(?!(firebase|@firebase)/)'], };
排查方向
- 确认 Firebase 版本:v9+ 为 ES 模块,v8 为 CommonJS,处理逻辑不同
- 检查
package.json中的type字段:若为"module",需在 Jest 中开启 ESM 支持(添加extensionsToTreatAsEsm: ['.ts', '.tsx']) - 验证 Jest 配置是否正确加载:可通过
jest --showConfig命令查看最终生效的配置
内容的提问来源于stack exchange,提问作者Atticus29
相关产品推荐
相关产品推荐

