Setting up Jest with ESM

Written by Rico Sta. Cruz
(@rstacruz) · 21 Apr 2021

Here are some different ways on how to set up Jest to support ESM. This applies for Jest v25, Node v13, and Babel v7.

Note: This article was written with Node v14 in mind (2021), things may have changed since.

Method A: Native Node.js support

Node v14 and Jest v26 support ESM natively with the --experimental-vm-modules flag. Install cross-env, then add NODE_OPTIONS to the scripts.test in package.json 2. See the Jest documentation for more info (jest.io).

Terminal window
yarn add --dev cross-env
package.json
"scripts": {
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
}

Method B: Using Babel

Add babel-jest. Configure Babel. We’ll use env.test here so not to interfere with your build process.

Terminal window
yarn add --dev \
@babel/core \
@babel/plugin-transform-modules-commonjs \
babel-jest
babel.config.js
module.exports = {
env: {
test: {
plugins: ['@babel/plugin-transform-modules-commonjs'],
},
},
}
jest.config.js
module.exports = {
transform: {
'^.+\\.[t|j]sx?$': 'babel-jest',
},
}

Method C: Using jest-esm-transformer

Add jest-esm-transformer - this is a preset configuration of Babel to support ESM transpilation.

Terminal window
yarn add --dev jest-esm-transformer
jest.config.js
module.exports = {
transform: {
'\\.m?jsx?$': 'jest-esm-transformer',
},
}

Method D: Using standard-things/esm

As of March 2020, using esm is currently not possible. Follow these threads for details.

Method E: Using buble

See buble-jest. Buble is an alternative to Babel. Note that as of 2021, this package hasn’t been updated since 2018.

Written by Rico Sta. Cruz

I am a web developer helping make the world a better place through JavaScript, Ruby, and UI design. I write articles like these often. If you'd like to stay in touch, subscribe to my list.

Comments

More articles

← More articles