node16 and Jest with ES6+ modules

I’ve run into this a few times, so leaving some notes for myself for next time,

By default, attempting to use “import x from ‘y’ ” style ES6 module imports with Jest will give you this error:

SyntaxError: Cannot use import statement outside a module

With node16, support for modules is added with the experiemental-vm option, so update your package.json to add a script executing jest with this flag:

"test": "node --experimental-vm-modules node_modules/.bin/jest"

and then also in your package.json, add:

  "type": "module",

If you search for the ‘cannot use import statement outside a module error there are plenty of recommendations, including more elaborate babel transpile ES6 modules to CommonJS style requires.

Depending what you’re doing maybe you’ll need some of the other approaches too, but I found the above 2 steps to be the bare minimum

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.