单仓多包项目中Jest报SyntaxError: Unexpected token 'export'求助
解决Monorepo中NextJS Jest测试识别ES模块语法的问题
方案1:让Jest转译本地Monorepo包
Jest默认会跳过node_modules目录下的文件转译,但Monorepo中的本地依赖(比如web-core、web-ui)通常是未编译的TS/ES模块源码,导致Jest无法识别export语法。需要修改Jest配置,指定转译这些本地包:
修改web-app/jest.config.js:
const nextJest = require('next/jest') const createJestConfig = nextJest({ dir: './', }) const customJestConfig = { setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'], // 配置模块别名,指向本地包源码路径 moduleNameMapper: { '^web-core$': '<rootDir>/../web-core/src', '^web-ui$': '<rootDir>/../web-ui/src', }, // 让Jest不忽略本地包的转译 transformIgnorePatterns: [ '/node_modules/(?!web-core|web-ui)', ], } module.exports = createJestConfig(customJestConfig)
注意:如果你的本地包用了@xxx/web-core这类带 scope 的包名,需要把web-core换成对应的包名前缀。
方案2:为本地包生成CommonJS编译产物
给web-core和web-ui添加编译步骤,输出CommonJS格式的产物,让Jest可以直接识别:
- 修改
web-core/tsconfig.json,配置CommonJS编译输出:
{ "compilerOptions": { "module": "CommonJS", "outDir": "./dist/cjs", "declaration": true, "declarationDir": "./dist/types" }, "include": ["src/**/*"] }
- 在
web-core/package.json中指定多入口,并添加构建脚本:
{ "main": "./dist/cjs/index.js", // Jest优先读取CommonJS入口 "module": "./dist/esm/index.js", // 供NextJS等ES模块环境使用 "types": "./dist/types/index.d.ts", "scripts": { "build": "tsc && tsc --module ESNext --outDir dist/esm" } }
- 执行
web-core的构建命令npm run build,再运行web-app的Jest测试即可。
方案3:切换Jest为ES模块模式
如果项目整体采用ES模块规范,可以配置Jest使用ES模块:
- 在
web-app/package.json中添加:
{ "type": "module" }
- 将
jest.config.js重命名为jest.config.mjs,改用ES模块语法:
import nextJest from 'next/jest' const createJestConfig = nextJest({ dir: './', }) const customJestConfig = { setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'], moduleNameMapper: { '^web-core$': '<rootDir>/../web-core/src', '^web-ui$': '<rootDir>/../web-ui/src', }, } export default createJestConfig(customJestConfig)
- 确保
ts-jest、jest等依赖为最新版本,避免兼容性问题。
内容的提问来源于stack exchange,提问作者Hasnain Ali
相关产品推荐
相关产品推荐

