公开一个全局命令以从节点包运行脚本

Ami*_*ner 1 command-line node.js npm

我正在构建一个 npm 包,我希望它使用自己的命令运行。

假设我的包的名称是hello-world并且它在 package.json 中有一个名为start的脚本,该脚本运行:

node index.js
Run Code Online (Sandbox Code Playgroud)

我想要的是从命令行能够编写一些将运行此脚本的自定义命令。

例如,写hello-worldcmdwill do 中npm run start

一个很好的例子是nodemon包。

pra*_*ran 7

您必须bin在 package.json 中添加字段以公开可以链接到任何可执行文件(如 js 文件)的全局命令。

示例 package.json

{
  "name": "hello-world",
  "version": "1.0.0",
  "description": "hello-world cli client",
  "bin": "index.js"
}
Run Code Online (Sandbox Code Playgroud)

那么你的 npm 模块应该全局安装在你的系统中,如下所示

npm pack (Optional.required only for local development)


npm install -g hello-world-1.0.0.tgz
Run Code Online (Sandbox Code Playgroud)

现在您应该能够通过运行命令来运行您的脚本 hello-world

注意:可执行脚本 ieindex.js应该以一行开头#!/usr/bin/env node