如何开发CLI工具

258 阅读1分钟

1、创建npm模块

npm init -y

2、bin入口文件

在package.json中增加bin对象

{
    "name": "@toy/cli",
    "version": "0.0.1",
    "description": "cli tools for toy",
    "scripts": {
        "test": "echo \"Error: run tests from root\" && exit 1",
        "dev": "tsc -w"
    },
    "bin": {
        "toy": "bin/toy"
    },
    "engines": {
        "node": ">=8"
    }
}

3、创建node脚本文件

创建node.js脚本文件,在js的首行设置如下代码:

#! /usr/bin/env node

4、全局安装

执行npm install -g 命令,将toy-cli安装到全局。
这样在任意位置输入toy命令,就可以执行你./bin/toy文件中的代码了

5、重复安装报错

有时如果之前已经做过npm i -g的操作,后续命令会失效,需要重新安装,重复安装会报这个错

npm ERR! path /usr/local/bin/toy
npm ERR! code EEXIST
npm ERR! Refusing to delete /usr/local/bin/toy: ../lib/node_modules/@toy/cli/bin/toy symlink target is not controlled by npm /usr/local/lib/node_modules/@toy/cli
npm ERR! File exists: /usr/local/bin/toy
npm ERR! Move it away, and try again.

可以使用如下命令解决
先删除bin目录下的包,在重新安装

// 删除全局下的toy
rm -f /usr/local/bin/toy
// 重新安装
npm i -g