KernelDeimos
KernelDeimos

Reputation: 617

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.

Upvotes: 6

Views: 1598

Answers (2)

Filip Seman
Filip Seman

Reputation: 1764

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.

Upvotes: 2

KernelDeimos
KernelDeimos

Reputation: 617

I just made a subdirectory with its own package.json that has "type": "module" set, so that it doesn't break any commonjs scripts outside of it but everything inside can import other es6 modules.

So yes, everything is fundamentally broken but there is a workaround.

Upvotes: 1

Related Questions