resolve-cli-args
A simple function to resolve cli arguments.
Install
npm i resolve-cli-args
Usage
import { resolveCliArgs } from 'resolve-cli-args'
const { args } = resolveCliArgs(process.argv.slice(2))
if (args['--help'] || args['-h']) {
// print help message
}
The type of the return value is:
interface ResolvedCliArgs {
/**
* An object containing argument names and their values.
*/
args: Record<string, string[] | undefined>
/**
* A list of values without option names.
*/
unnamedValues: string[]
}
If the option do not have any values, the value of this option will be set to an empty array.
Examples
import { resolveCliArgs } from 'resolve-cli-args'
console.log(resolveCliArgs([
'--config', 'config.json', 'input.txt', 'output.txt'
]))
// {
// args: { '--config': [ 'config.json' ] },
// unnamedValues: [ 'input.txt', 'output.txt' ]
// }
console.log(resolveCliArgs([
'--log-level=2', '--type', 'typescript'
]))
// {
// args: { '--log-level': [ '2' ], '--type': [ 'typescript' ] },
// unnamedValues: []
// }
console.log(resolveCliArgs([
'--compress', '-q'
]))
// { args: { '--compress': [], '-q': [] }, unnamedValues: [] }
console.log(resolveCliArgs([
'--a', '1', 'a', '--b', '2', 'b', '--c=3', 'c'
]))
// {
// args: { '--a': [ '1' ], '--b': [ '2' ], '--c': [ '3' ] },
// unnamedValues: [ 'a', 'b', 'c' ]
// }
console.log(resolveCliArgs([
'--ext=.js', '--ext=.ts', '--ext', '.jsx', '--ext', '.tsx'
]))
// {
// args: { '--ext': [ '.js', '.ts', '.jsx', '.tsx' ] },
// unnamedValues: []
// }
console.log(resolveCliArgs([
'--var=a=b', '--var', '---c=d'
]))
// { args: { '--var': [ 'a=b', '---c=d' ] }, unnamedValues: [] }
console.log(resolveCliArgs([
'--a=1', '--', '--c=d', '-e', 'f'
]))
// {
// args: { '--a': [ '1' ], '--': [ '--c=d', '-e', 'f' ] },
// unnamedValues: []
// }
Note: The string that starts with
"--"
or"-"
will be treated as option name (not including the string that starts with"---"
).