I'm having trouble with a syntax error while trying to integrate mdast-util-from-markdown into my Jest tests for a TypeScript project. I am seeking a solution that does not involve using Babel.
The code functions properly when using ts-node.
Issue:
Running my Jest tests results in the following error:
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";
Current Setup
Configuration:
tsconfig.json
:
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs", // Also tried "esnext"
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"include": [
"src/**/*",
"test/**/*"
]
}
jest.config.cjs
(also attempted 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']
};
Runner
npx jest
NODE_OPTIONS='--loader ts-node/esm' npc jest
Tried Solutions
- Adjusting module settings in tsconfig.json (e.g., changing to "esnext", "commonjs")
- Modifying jest.config.js to
- handle ES module syntax,
transformIgnorePatterns: ['<rootDir>/node_modules/(?!unist-util-visit)'],
- Attempted using Babel, despite preferring not to, and still encountering the error :/
Question:
How can I configure Jest and TypeScript to work seamlessly with mdast-util-from-markdown without facing the 'Unexpected token' issue, preferably without introducing Babel into my setup?
Edit:
Found success with:
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