Search code examples
node.jses6-modules

How to run ".js" file in node as esmodule without setting type in package.json or changing the extension


I'm determined to find a way to do this. Here's why:

I'm writing tests for .js files which are bundled with webpack for a browser client. I would like to run these tests in nodejs. There is a "build.js" script which is NOT using es6 modules, it's a commonjs module - so updating package.json would break it.

Is there a way to do this or is everything fundamentally broken?

Edit: after my workaround it still doesn't really work 'cause now webpack is broken.


Solution

  • Since Node v21.1.0, see release.

    You can use --experimental-detect-module flag, which eliminates the requirement for "type": in package.json or the use of .mjs/.cjs extensions.