使用Jest测试Backstage插件遇ESM语法解析错误求助
解决Jest无法解析Backstage .esm.js模块的问题
问题根源
Jest默认跳过node_modules目录下文件的转译,但Backstage核心插件(如@backstage/core-plugin-api)输出ES模块格式(.esm.js),而Jest默认基于CommonJS模块系统运行,因此遇到export语法时会抛出语法错误。
解决方案
1. 修正Jest配置(jest.config.cjs)
你的transformIgnorePatterns正则匹配规则有误,同时ts-jest与babel-jest的配置存在冲突,调整如下:
module.exports = { preset: 'ts-jest/presets/js-with-babel', // 整合ts-jest与babel的预设,避免冲突 transform: { '^.+\\.(ts|tsx)$': 'ts-jest', // TypeScript文件用ts-jest处理 '^.+\\.(js|jsx|esm\\.js)$': 'babel-jest', // JS/ESM文件用babel转译 }, transformIgnorePatterns: [ // 让Jest转译node_modules中@backstage开头的所有.esm.js文件 '/node_modules/(?!@backstage/).+\\.(js|jsx|esm\\.js)$', '/node_modules/(?!@module-name/plugin-search).+\\.(js|jsx|esm\\.js)$' ], testEnvironment: 'jsdom', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], setupFilesAfterEnv: ['./Unit-tests/src/setupTests.ts'], testMatch: ['*/?(.)+(spec|test).ts?(x)'], };
2. 优化Babel配置(babel.config.json)
确保Babel能将ES模块转换为Jest支持的CommonJS格式:
{ "presets": [ ["@babel/preset-env", { "targets": { "node": "current" // 适配当前Jest运行的Node版本 } }], "@babel/preset-typescript", "@babel/preset-react" ] }
3. 确认TypeScript配置(tsconfig.json)
保持测试环境的模块系统与Jest兼容:
{ "compilerOptions": { "target": "ES6", "module": "commonjs", // 维持CommonJS适配Jest "moduleResolution": "node", "baseUrl": "./src", "paths": { "@components/*": ["components/*"] }, "typeRoots": ["./node_modules/@types", "./src/types"], "esModuleInterop": true, "strict": true, "declaration": true }, "include": ["./Unit-tests/src/**/*.ts", "src/**/*.tsx"], "exclude": ["node_modules", "dist"] }
验证步骤
- 删除
node_modules和锁文件(package-lock.json/yarn.lock),重新安装依赖 - 运行测试命令,检查是否仍存在
Unexpected token 'export'错误
内容的提问来源于stack exchange,提问作者Jean Carlos Ramirez
相关产品推荐
相关产品推荐

