ES 模块上的 Node.js yargs 包

wmr*_*ood 2 node.js yargs es6-modules

亚格斯示例:

require('yargs')
  .scriptName("pirate-parser")
  .usage('$0 <cmd> [args]')
  .command('hello [name]', 'welcome ter yargs!', (yargs) => {
    yargs.positional('name', {
      type: 'string',
      default: 'Cambi',
      describe: 'the name to say hello to'
    })
  }, function (argv) {
    console.log('hello', argv.name, 'welcome to yargs!')
  })
  .help()
  .argv
Run Code Online (Sandbox Code Playgroud)

我该如何在 ESM 中执行此操作?

提前致谢

Jay*_*Are 6

Yarg 的package.jsonimports./index.mjs导出 aYargsFactory而不是模块中的实例CommonJS

所以我们不仅需要import yargs from 'yargs/yargs';,还需要调用yargs并将其传递给process.argv解析(切片以删除节点 exe 和脚本路径)。

import yargs from 'yargs/yargs';

yargs(process.argv.slice(2))
  .scriptName("pirate-parser")
  .usage('$0 <cmd> [args]')
  .command('hello [name]', 'welcome ter yargs!', (yargs) => {
    yargs.positional('name', {
      type: 'string',
      default: 'Cambi',
      describe: 'the name to say hello to'
    })
  }, (argv) => {
    console.log('hello', argv.name, 'welcome to yargs!')
  })
  .help()
  .argv
Run Code Online (Sandbox Code Playgroud)

至少这对我有用。