Jascha Ehrenreich
Jascha Ehrenreich

Reputation: 557

load ecmascript module (.mjs file) as main entry of nodejs cli

is there a way to use an ecmascript module file as the main entry file to a cli exported using the package.json bin entry?

i guess i would need to somehow provide the --experimental-modules flag, but i can not figure out a way to do this without wrapping the mjs file into a js file and then calling the mjs file via

#!/usr/bin/env node
// pseudocode
child_process.spawn(
  'node', 
  ['--experimental-modules', 'bin.mjs'], 
  { stdio: 'inherit' }
)

given the overhead of calling child_process.spawn, i would love to be able to replace those wrappers in my libraries.

edit: please not that my cli has to be installable as an executable using npm i -g, which, afaik, makes it impossible to pass any command line flags to the node process (see answer that i will not be able to use)

edit2: figured i should leave a link to the related library here too @magic/cli, this is my current approach (i include a bin.js file that child_process.spawns a mjs file)

Upvotes: 2

Views: 2817

Answers (2)

Konstantin Pelepelin
Konstantin Pelepelin

Reputation: 1562

Node 13 enables --experimental-modules by default, so #!/usr/bin/env node is enough. However, a warning is still emitted.

(node:23260) ExperimentalWarning: The ESM module loader is experimental.

Upvotes: 1

Sudipto Ghosh
Sudipto Ghosh

Reputation: 86

You can install the esm module and then require it when running the code i.e. instead of --experimental-modules, you can use -r esm instead. You would then run your code as node -r esm bin.mjs.

Upvotes: 1

Related Questions