minimist 是一个常用的 Node.js 库,用于解析命令行参数
// for CJS
const argv = require('minimist')(process.argv.slice(2));
// for ESM
// import minimist from 'minimist';
// const argv = minimist(process.argv.slice(2));
console.log(argv);
与选项无关的 _ 将转换为字符串 我们可以通过第二个选项参数opts的.string属性指定参数始终作为字符串处理:
const argv = minimist(process.argv.slice(2), { string: ['_'] })
-
string: 指定哪些参数应该总是被当作字符串处理{string: ['_','v']}_和v的值都会作为字符串处理
node index.js -a 1 -b 2 123123 // { _: [ '123123' ], a: 1, b: 2 } -
boolean: 指定哪些参数应该被当作布尔值处理- 字符串或始终将其视为布尔值的字符串数组。如果
true,则将所有没有等号的双破折号参数视为布尔值(例如,影响--foo,而不是-f或--foo=bar) {boolean: ['foo']}对foo进行判断处理
// 影响 node index.js -a 1 --foo 123 // { _: [ 123 ], foo: true, a: 1 } // 不影响 node index.js -a 1 --foo=123 // { _: [], foo: true, a: 1 } node index.js -a 1 --f 123 // { _: [], foo: false, a: 1, f: 123 } - 字符串或始终将其视为布尔值的字符串数组。如果
-
alias: 为参数设置别名{alias: {v: 'version'}}将version设置别名v
node index.js -a 1 -v 123 // { _: [], a: 1, v: 123, version: 123 } node index.js -a 1 --version 123 // { _: [], a: 1, version: 123, v: 123 } -
default: 为参数设置默认值{debault: {version: '123'}}设置version为123
node index.js -a 1 // { _: [], a: 1, version: 123 } -
stopEarly: 当设置后,minimist将会在遇到第一个非选项参数后停止解析{stopEarly: true}
node index.js -a 1 bb -c 22 // { _: [ 'bb', '-c', '22' ], a: 1 } 遇到bb后就没有解析选项参数了 node index.js -a 1 -b 2 cc 22 // { _: [ 'cc', '33' ], a: 1, b: 2 } 正常解析 -
--: 如果设置为true, 则将--后的所有参数放入argv._- 当
opts['--']为真时,用--之前的所有内容填充argv._,用--之后的所有内容填充argv['--']。以下是一个例子:
- 当
> require('./')('one two three -- four five --six'.split(' '), { '--': true })
{
_: ['one', 'two', 'three'],
'--': ['four', 'five', '--six']
}
请注意,即使设置了 opts['--'] ,参数的解析仍然会在 -- 之后停止。
如有不对的地方欢迎各位大佬指正