Babel 7 dynamic config – making Babel work with esm, Jest, JSX, and Preact server-side rendering
Babel enables use of modern JS code (ES2015 — ES2018) in browsers and environments that don’t inherently support it using a technique known as transpiling. One of the features I enjoy about Babel 7 (currently at beta 46) is the ability to provide a dynamic .babelrc.js
configuration file rather than a statically defined .babelrc
(JSON) file.
I recently adopted esm (for ES Modules support in Node.js; import
and export
) on the Verses for Life website. One of the challenges I ran into with using esm
was getting my server to use esm
by default for development and production work, but still having my tests work. (For general esm
setup, see esm on npm.)
I’d already decided in the past to use Jest, but, unfortunately, Jest doesn’t play nicely with esm
by default and Jest doesn’t support a --require
flag like many other JS testing libraries. So what to do?
The solution is allowing Jest to use Babel to transpile the modules during testing (so you avoid those pesky “unexpected token import” errors), but keeping esm
in place for all your other dev and production work.
I set up my Babel 7 config (.babelrc.js
) to use Babel to handle modules only in test
mode, but esm
does the work everywhere else.
.babelrc.js code
https://gist.github.com/calvinf/e314719e3913bd46752c3dc78ccfac2e
This approach enabled my tests to work again. The downside of this approach is that the way modules are loaded in testing doesn’t match my other environments. You’ll want to ensure you have appropriate integration tests (a la Puppeteer) to ensure your site works end-to-end.
If you’re early on in deciding your tooling, you can look at the list of the many other test libraries supported by esm
and maybe you won’t need this work-around.