简体   繁体   English

ES 模块上的 Node.js yargs package

[英]Node.js yargs package on ES modules

Yargs example:雅格斯示例:

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

how would I do this in ESM?我将如何在 ESM 中执行此操作?

Thanks in advance提前致谢

Yarg'spackage.json points import s at ./index.mjs which exports a YargsFactory rather than an instance as in the CommonJS module. Yarg 的package.json指向import s at ./index.mjs导出一个YargsFactory而不是CommonJS模块中的一个实例。

So we need not only to import yargs from 'yargs';所以我们不仅需要import yargs from 'yargs'; , but also to call yargs and pass it the process.argv to parse (slicing to remove the node exe and script paths). ,还要调用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

At least that worked for me.至少那对我有用。

All you need to do is change require to import .您需要做的就是将require更改为import

import yargs from 'yargs'

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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