简体   繁体   中英

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM