2

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?

Thanks in advance

wmrisgood
  • 31
  • 2

2 Answers2

4

Yarg's package.json points imports at ./index.mjs which exports a YargsFactory rather than an instance as in the CommonJS module.

So we need not only to import yargs from 'yargs/yargs';, but also to call yargs and pass it the process.argv to parse (slicing to remove the node exe and script paths).

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.

jaybeeuu
  • 1,013
  • 10
  • 25
0

All you need to do is change require to 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
Mark Skelton
  • 3,663
  • 4
  • 27
  • 47
  • This fails for me unfortunately. As per the comment above, i also see `"TypeError: yargs.scriptName is not a function"`. This is when runnning latest yargs, in node 18, with "type": "module" in my package.json . – jaybeeuu Nov 16 '22 at 21:42
  • I think it's because we're getting a `YargsFactory` rather than a yargs instance (see https://github.com/yargs/yargs/blob/main/index.mjs#L7). I needed to call `yargs()` to get it to stop failing, but it still didn't work. It doesn't seem to read the argv properly... – jaybeeuu Nov 16 '22 at 21:52