场外
图书馆很少增加 rg 包括分析环境变量和从 args 选项创建 json-schema 的能力.
使用量
您的类型脚本程序可能看起来像 :
import os from 'os'
import path from 'path'
import fs from 'fs'
import yargs, { asYargs, generateSchema, cleanupConfig, parseEnv } from '@bpinternal/yargs-extra'
const yargsSchema = asYargs({
remoteUrl: {
type: 'string',
description: 'URL to remote server'
},
oauth: {
type: 'boolean',
description: 'Whether or not to use oauth'
}
})
const jsonSchemaLocation = path.join(os.homedir(), '.myapp', 'myapp.config.schema.json')
const configFileLocation = path.join(process.cwd(), 'myapp.config.json')
const stringify = (x) => JSON.stringify(x, null, 2)
void yargs
.command(
'init',
'Init configuration file',
(yargs) => yargs.options({}),
async () => {
const jsonSchema = generateSchema(yargsSchema)
fs.writeFileSync(jsonSchemaLocation, stringify(jsonSchema))
fs.writeFileSync(configFileLocation, stringify({ $schema: jsonSchemaLocation }))
}
)
.command(
'build',
'Build something',
(yargs) => yargs.options(yargsSchema),
async (yargsArgv) => {
const yargsEnv = parseEnv(yargsSchema, 'MYAPP')
const yargsFile = fs.existsSync(configFileLocation)
? JSON.parse(fs.readFileSync(configFileLocation, 'utf-8'))
: undefined
// cli args will override json config, which will also override env variables
const resolved = cleanupConfig(yargsSchema, { ...yargsEnv, ...yargsFile, ...yargsArgv })
console.log(resolved)
// ...
}
)
.help().argv
使用上面的这个程序,您可以尝试几种不同的方式传递参数:
./myapp init # will create an empty config file
code ./myapp.config.json # will open your config file in vscode with intellisense
MYAPP_REMOTE_URL=http://lol.com ./myapp build # { remoteUrl: 'http://lol.com' }
MYAPP_REMOTE_URL=http://lol.com ./myapp build --oauth # { remoteUrl: 'http://lol.com', oauth: true }
MYAPP_REMOTE_URL=http://lol.com ./myapp build --remote-url http://localhost:3100 # { remoteUrl: 'http://localhost:3100' }
当在 vscode 中打开配置文件时,你会得到intellisense:

免责声明
此软件包将在 @bpinternal 组织。 这个组织的所有软件包都用于 瓶装 内部的团队 并不适合我们的社区。 由于这些软件包适合我们自己的使用情况,它们可能不稳定的API,在没有警告的情况下接受中断的更改,文件很少,缺乏以社区为重点的支持。 然而,这些软件包仍然被故意公开,其重要原因如下: 我们爱开源. 因此,如果您想要安装或叉出这个软件包,就完全可以自由操作。 我们强烈建议你正确标记你的版本.
博讯工程组.