8

I'm new to Node.js and I'm learning some basics now. I'm trying to use some typescript code to convert into .js code later.

I wrote this simple code to test

    import * as fs from 'fs'


    const argv = require('yargs')
                .alias('f', 'filename')
                .alias('c', 'content')
                .demandOption('filename')
                .demandOption('content')
                .argv

    fs.writeFile(argv.filename, argv.content, (error)=>{
        if(error) 
            throw error
        console.log(`File ${argv.filename} saved.`)
    })

And this works fine. But when I change the line require('yargs') to import, like below:

   import * as fs from 'fs'
   import * as yargs from 'yargs'

    const argv = yargs
                .alias('f', 'filename')
                .alias('c', 'content')
                .demandOption('filename')
                .demandOption('content')
                .argv

    fs.writeFile(argv.filename, argv.content, (error)=>{
        if(error) 
            throw error
        console.log(`File ${argv.filename} saved.`)
    })

I'm getting this error:

Argument of type 'unknown' is not assignable to parameter of type 'string | number | Buffer | URL'.

Type '{}' is missing the following properties from type 'URL': hash, host, hostname, href, and 9 more.ts(2345)

Does anybody know what's the difference between using module/import that is causing this error? For fs library both ways work fine in this example.

2

5 Answers 5

12

Here is the corrected code for anyone still wondering how to use ES6 module syntax with Yargs. I had to add some type information with option() to avoid errors. Refer to a Github discussion for more information.

import fs from 'fs';
import _yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
const yargs = _yargs(hideBin(process.argv));

(async () => {
    const argv = await yargs
        .option('filename', { type: 'string', require: true })
        .option('content', { type: 'string', require: true })
        .alias('f', 'filename')
        .alias('c', 'content')
        .argv;

    fs.writeFile(argv.filename, '' + argv.content, error => {
        if (error) throw error;
        console.log(`File ${argv.filename} saved.`);
    });
})();
Sign up to request clarification or add additional context in comments.

2 Comments

this has all the correct parts for me to get past my error, I compared to what I was trying to do and fixed. I converted const yargs = require('yargs/yargs') to import yargs from 'yargs/yargs'; which throws an error.
If you don't like the _ naming convention, I find yargsFactory is a good name for this.
3

Have you tried installing yargs typings, by running the following command?

npm install --save @types/yargs

Comments

1

I think ES6 compliant import is still not supported and only require works.

import yargs from 'yargs'
console.log(yargs.argv)

$ node app.js
undefined

1 Comment

Why not console.log(yargs)?
0

You need to set the type of args from argv. Try to change your core to:

const argv = yargs
        .option('filename', {
            alias: 'f',
            demandOption: true,
            describe: 'Nome do arquivo',
            type: 'string'
        })
        .option('content', {
            alias: 'c',
            demandOption: true,
            describe: 'Conteudo',
            type: 'string'
        })
        .argv

1 Comment

Please do not use code snippets for scripts that cannot be run without external dependencies or platforms. Use proper code formatting [Ctrl+K] instead: single backticks (“`”) for one-liners, property names and methods, code fences (“````”) for code blocks. Also please avoid chit-chat in questions, SO is not a forum, it is a Q&A website.
0

i found this solution to use Yargs with module type

import yargs from 'yargs/yargs';  // (v17.7.2)

const argv = yargs(process.argv.slice(2))
    .option('dev', {
        alias: 'd',
        type: 'boolean',
        describe: 'dev mode'
    })
    .argv;

console.log(argv.dev); // will be true when starting "node index.js --dev"

source for typescript, usable in NodeJS with "type": "module" https://github.com/yargs/yargs/blob/main/docs/typescript.md

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.