javascriptnode.jscommand-line-interfacees6-modulesmjs

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)


Solution

  • 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.