babel-jest does not transpile import/export in node_modules when Babel 7 is used
See original GitHub issue🐛 Bug Report
I started getting the dreaded SyntaxError: Unexpected token import
error again for lodash-es
. And I spent hours debugging it, because I already had .babelrc and package.json:jest configured properly ("modules": "commonjs"
, a jest.transform
for babel-jest
, and transformIgnorePatterns
set to not ignore node_modules/lodash-es
).
After a lot of debugging and a little searching, it appears that Babel 7 has stopped using the project’s .babelrc
code in node_modules
. This means that all the previous suggestions to just tell transformIgnorePatterns
to transpile certain packages in node_modules and set "modules": "commonjs"
in the test env to make WebPack import
work with jest no longer work.
To Reproduce
Steps to reproduce the behavior:
- Import an es-modules using library like
lodash-es
into your project - Write a Jest test that imports the file you import the es-modules using package
- Setup a recent version of Babel 7
- Configure .babelrc to use the env preset to transpile ES6 modules to CommonJS
- Configure Jest to transform .js files with
babel-jest
andtransformIgnorePatterns
to not ignore the es-modules using package
Expected behavior
When babel-jest is used to transpile ES-modules using packages like lodash-es it should transpile the imports to CommonJS so they work with Jest.
Practically I believe it should be sufficient to add transform-modules-commonjs
to the plugins list that babel-jest
uses when the filename is a node_modules
file and Babel 7 is used. This would also fix the fact that it’s not good practice for the project’s .babelrc
(which may also include plugins for non-standard things like JSX and flow) to be used just to transpile ES6 / modules code in packages.
Link to repl or repo (highly encouraged)
https://gist.github.com/dantman/820f6232acc6f53bd1e57d21b09e1f89
Run npx envinfo --preset jest
Paste the results here:
System:
OS: macOS Sierra 10.12.6
CPU: x64 Intel(R) Core(TM) i5-7267U CPU @ 3.10GHz
Binaries:
Node: 9.11.1 - ~/.nvm/versions/node/v9.11.1/bin/node
Yarn: 1.6.0 - /usr/local/bin/yarn
npm: 5.6.0 - ~/.nvm/versions/node/v9.11.1/bin/npm
npmPackages:
jest: ^22.4.4 => 22.4.4
Issue Analytics
- State:
- Created 5 years ago
- Reactions:136
- Comments:58
Top GitHub Comments
For the record, I was able to fix the issue of my module in the
node_modules
folder not compiling properly by:.babelrc
tobabel.config.js
andmodule.exports
the config objecttransformIgnorePatterns
to my Jest config:Renaming .babelrc to babel.config.js worked for me