TypeScript项目Jest集成mdast-util-from-markdown报错,求无Babel解决方案
解决TypeScript Jest测试中集成mdast-util-from-markdown的ES模块语法错误
问题场景
在TypeScript项目的Jest测试中集成mdast-util-from-markdown时出现语法错误,代码通过ts-node运行正常,但Jest执行时报错。
错误详情
Details: /Users/dudeman/ac/_utils/md-hierarchical-parser/node_modules/mdast-util-from-markdown/index.js:2 export {fromMarkdown} from './lib/index.js' ^^^^^^ SyntaxError: Unexpected token 'export' > 1 | import { fromMarkdown } from "mdast-util-from-markdown";
当前配置
tsconfig.json
{ "compilerOptions": { "target": "es2017", "module": "commonjs", // 也尝试过"esnext" "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true }, "include": [ "src/**/*", "test/**/*" ] }
jest.config.cjs(也曾尝试jest.config.js)
module.exports = { preset: 'ts-jest', testEnvironment: 'node', globals: { 'ts-jest': { useESM: true } }, moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1' }, transform: { '^.+\\.ts$': 'ts-jest' }, extensionsToTreatAsEsm: ['.ts'] };
运行命令
npx jestNODE_OPTIONS='--loader ts-node/esm' npx jest
已尝试方案
- 修改tsconfig.json的
module配置(如"esnext"、"commonjs") - 调整jest.config.js:
- 配置ES模块语法处理
- 添加
transformIgnorePatterns: ['<rootDir>/node_modules/(?!unist-util-visit)']
- 尝试引入Babel,但仍报错
需求
配置Jest和TypeScript,使其能正常配合mdast-util-from-markdown运行,避免Unexpected token 'export'错误,且不引入Babel。
可行配置方案
以下配置可解决问题:
tsconfig.json
{ "compilerOptions": { "strict": true, "target": "ES2022", "module": "esnext", "moduleResolution": "node", "lib": ["esnext"], "types": ["node", "jest"], "skipLibCheck": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "declaration": true, "allowSyntheticDefaultImports": true }, "ts-node": { "experimentalSpecifierResolution": "node", "transpileOnly": true, "esm": true }, "exclude": ["node_modules", "lib"] }
jest.config.js
module.exports = { preset: 'ts-jest', testEnvironment: 'node', transform: { '^.+\\.(ts|tsx)?$': ['ts-jest', { useESM: true }], }, moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1' }, extensionsToTreatAsEsm: ['.ts'] };
package.json
{ "type": "module", "dependencies": {}, "devDependencies": { "@typescript-eslint/eslint-plugin": "^6.13.1", "@typescript-eslint/parser": "^6.13.1", "@types/jest": "29.5.10", "eslint": "^8.55.0", "jest": "29.7.0", "ts-jest": "29.1.1", "ts-node": "^10.9.1", "typescript": "^5.2.2" } }
最终运行命令
jest --env=node --colors --coverage test
内容的提问来源于stack exchange,提问作者Ashley Coolman
相关产品推荐
相关产品推荐

