Tha*_*ano 8 node.js typescript yargs
我是 Node.js 新手,现在正在学习一些基础知识。我稍后尝试使用一些打字稿代码转换为 .js 代码。
我写了这个简单的代码来测试
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.`)
})
Run Code Online (Sandbox Code Playgroud)
这很好用。但是当我更改需要导入的行require('yargs')时,如下所示:
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.`)
})
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
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)
Run Code Online (Sandbox Code Playgroud)
有谁知道使用导致此错误的模块/导入之间有什么区别?对于 fs 库,在本例中两种方法都可以正常工作。
对于那些仍然想知道如何将 ES6 模块语法与 Yargs 一起使用的人来说,这里是更正后的代码。我必须使用 option() 添加一些类型信息以避免错误。请参阅Github 讨论以获取更多信息。
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.`);
});
})();
Run Code Online (Sandbox Code Playgroud)
小智 0
您需要从 argv 设置 args 的类型。尝试将您的核心更改为:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8070 次 |
| 最近记录: |