babel: Babel-node not working with "type": "module" in package.json

I have the following script that I’m running with npx babel-node script.js

let a = 0;
let b = 1;
console.log(a ?? b);

It executes fine with my babel config

{
	"plugins": ["@babel/plugin-proposal-nullish-coalescing-operator"]
}

When I add “type”: “module” to my package.json file, the npx babel-node script.js command fails to run and I get the error SyntaxError: Unexpected token '?'.

So it seems specifying my package as module, prevents babel-node from loading the babel config?

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 23 (11 by maintainers)

Most upvoted comments

So what is the suggestion here? My understanding is that we use @babel/node for developing a node backend with babel configuration, and then we are supposed to compile the backend using the babel cli for production. In order to keep using import in my node app, I use "type": "module" for the compiling step… which breaks @bable/node and therefore development… this seems like an issue to me, shouldn’t this be reopened?

https://github.com/nicolo-ribaudo/babel-native-esm-demo

my eslint config, my rollup config

I don’t know if those tools support native ESM configs, but Babel does.

I would like to help out in this doc fix.

@nnmrts I think you misunderstood this issue. You can successfully use ES modules with Babel on Node.js and I’m doing it in different projects. You can use ES modules to write your Babel config.

The only thing that you cannot do is using the @babel/node and @babel/register packages.

This is a nasty issue once you run into it - this essentially is keeping me from being able to use newer javascript features and native ES modules alongside one another - it breaks babel-node which is used in development

The problem is if you set type: module in package.json then your babel.config.js must be in module format (or you will get Error while loading config - module is not defined error).

And babel config in esm format works fine with @babel/cli but not with @babel/register. So for now it is not possible to have type: module and using babel-node.

Should we close this issue since it has been solved in https://github.com/babel/website/pull/2177 ?

Worth add a note to https://babeljs.io/docs/en/babel-register that babel-register does not support compiling native Node.js es modules on the fly.