Importing packages written ESM
See original GitHub issueIs it possible to import packages that are written in ESM? For example in my TypeScript project I have a dependency to react-dates@next which is written in ECMAScript module syntax (import / export). In my webpack build everything works fine because webpack understands natively ESM. But in my Jest tests I get SyntaxError: Unexpected token import in
/my/project/node_modules/date-fns/esm/addDays/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import toDate from '../toDate/index.js'
One solution would be to include babel-jest as it’s written in the official Jest docs and modify my config to
"transform": {
  "^.+\\.js$": "babel-jest",
  "^.+\\.tsx?$": "ts-jest"
},
This works in my case but I don’t want to clutter my project with Babel stuff just for tests. Additionally the tests are getting really slow and Babel complains with
[BABEL] Note: The code generator has deoptimised the styling of "/Users/me/development/my-project/node_modules/ty
pescript/lib/typescript.js" as it exceeds the max of "500KB".
So it seems that Babel is transpiling *all my dependencies.
Is it possible to achieve the same with ts-jest? I also tried to modify my tsconfig.json to let TypeScript compile to "module": "commonjs" and set "transformIgnorePatterns": ["<rootDir>/node_modules/react-dates"] but this doesn’t work. It seems that the source files from date-fns doesn’t get passed to ts-jest. I could provide a small test project if you want.
Issue Analytics
- State:
 - Created 6 years ago
 - Reactions:4
 - Comments:26 (11 by maintainers)
 

Top Related StackOverflow Question
I think this does work but you need to get jest to transform these files using ts-jest - by default no files under node_modules are transformed but you can change this with configuration:
Will feed
node-modules/antd/*andnode_modules/rc-*/**through the transpiler. All other files under node_modules will be excluded as before.Then you need to tell ts-jest to transpile javascript files, so in tsconfig.json add
Hey @damianobarbati I ran into your issue with
nanoidtoday. Since that package doesn’t have a CommonJS export, I found using the ts-jest transform presetjs-with-tssolved the issue as it transforms all files to CommonJS. Transpiling JS files with Babel could also work e.g. via thejs-with-babelpreset.You’ll need to add
transformIgnorePatternswith an exclude pattern to ensurenanoidand other ES modules in node_modules get picked up. Also helps to havecheckJS: falsein your tsconfig set (at least for deps) to avoid error spam.