我正在创建一个 JavaScript 库,并且希望在使用 -g
标志安装时将其用作命令。问题是我怎样才能实现这种行为。我应该能够将其用作命令。
由于电子的行为方式如此,我想我可以引用 electron代码,但没有从发生的地方获取。
<小时/>我已经实现了以下行为
node_modules/nexam/index.js
module.exports = require("./lib/nexam");
node_modules/nexam/lib/nexam.js
'use strict'
exports = module.exports;
exports.sayHello = function(){
console.log("Hello World");
}
main.js
const nexam = require("nexam");
nexam.sayHello();
输出:
$ node main.js
Hello World
<小时/>
我想这样使用它
$ npm install -g nexam
$ nexam --version
nexam v1.0.0
$ nexam --sayHello
Hello World
最佳答案
这里有两件事需要处理。
- 将
bin
添加到package.json
文件
"bin": { "nexam": "./index.js" }
- 使用commander npm 包来读取 cli 命令。它非常容易使用。这是他们文档页面的片段。
var program = require('commander'); program .version('0.1.0') .option('-p, --peppers', 'Add peppers') .option('-P, --pineapple', 'Add pineapple') .option('-b, --bbq-sauce', 'Add bbq sauce') .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') .parse(process.argv); console.log('you ordered a pizza with:'); if (program.peppers) console.log(' - peppers'); if (program.pineapple) console.log(' - pineapple'); console.log(' - %s cheese', program.cheese);
祝一切顺利。
关于javascript - 像 Electronjs 一样在自定义 Node 模块中添加命令行行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56458384/