2

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)

2 Answers2

1

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.

Sudipto Ghosh
  • 76
  • 1
  • 6
  • 1
    this, whilst entirely valid and usable, would force the consumers of my cli to always type node -r esm cli.mjs though. and, unfortunately, in the case of globally installed cli's this would not help at all. thanks for the answer though :) – Jascha Ehrenreich May 15 '19 at 05:00
1

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.

Konstantin Pelepelin
  • 1,303
  • 1
  • 14
  • 29
  • thanks! https://github.com/magic/cli has been updated to leverage that fact by now, i just remembered this question and went here to answer it, and, as usual, so has already done so. – Jascha Ehrenreich Feb 11 '20 at 05:41