likes
comments
collection
share

Node.js 命令行工具开发指南:从零开始构建你的工具

作者站长头像
站长
· 阅读数 4

在当今软件开发的世界中,命令行工具越来越受欢迎。无论是自动化任务、快速处理数据还是执行各种操作,Node.js 提供了一个强大而灵活的平台来构建这样的工具。本指南将带领你一步步学习如何利用 Node.js 开发命令行工具,无需先前的经验。

1. 项目初始化

开始之前,确保你已经安装了 Node.js 和 npm(推荐使用 pnpm)。在你的命令行界面中,运行以下命令来初始化一个新的 Node.js 项目:

pnpm init
pnpm i -D typescript ts-node
pnpm i yargs
npx tsc --init

我们现在有了一个简单的 TypeScript 项目。接下来,我们可以创建我们的命令行工具的主文件 bin/index.js

#!/usr/bin/env node
'use strict';
const yargs = require('yargs');
const { hideBin } = require('yargs/helpers');
const pkg = require('../package.json')

const arg = hideBin(process.argv)
const cli = yargs(arg)

const args = cli
  .version(pkg.version)
  .usage('Usage: node-cli 【command】 <options>')
  .alias('h', 'help')
  .alias('v', 'version')
  .option('debug', {
    type: 'boolean',
    desc: 'load code with ts-node for debug',
  })
  .help()
  .strict()
  .argv


if (args.debug) {
  require('ts-node/register');
  const { main } = require('../src/index')
  main(args)
} else {
  const { main } = require('../dist/index')
  main(args)
}

接下来我们来定义 cli 具体逻辑结构,创建 src/index.ts 文件。

type Action = '';

export interface Options {
  _: [Action];
}

export function main(options: Options) {
  const { _: [action], ...rest } = options;
}

2. 命令行参数定义

接下来我们定义一个 command

const args = cli
  .version(pkg.version)
  .usage('Usage: node-cli 【command】 <options>')
  .alias('h', 'help')
  .alias('v', 'version')
  .command('init', 'Initialize project', {
    // 这里就是 init 命令携带的参数
    output: {
      type: 'string', // 类型
      alias: 'o', // 缩写
      default: './', // 默认值
      description: '输出目录', // 描述
    },
  })

创建 src/commands/init.ts.

export interface InitOptions {
  output: string;
}

export function init() {

} 

接下来我们在 src/index.ts 文件去进行处理

import { type InitOptions, init } from './commands/init'
type Action = 'init';

export interface Options extends InitOptions {
  _: [Action];
}

export function main(options: Options) {
  const { _: [action], ...rest } = options;
  
  if (action === 'init') {
    init(rest as InitOptions)
  }
}

3. 命令行常用工具

  • inquirer:用于创建交互式命令行界面的工具,可以创建各种类型的提示,例如选择、输入、确认等,使命令行工具更易于使用。
  • chalk:用于在命令行中添加彩色输出的工具,可以帮助美化命令行界面,提高可读性。
  • ora:用于在命令行中显示加载动画的工具,可用于指示长时间运行的任务的进度。
  • dotenv:用于从 .env 文件中加载环境变量的工具,可以帮助管理项目的配置和敏感信息。
  • shelljs:一个 Unix shell 命令的 JavaScript 实现,可以在 Node.js 中方便地执行 Shell 命令。
  • fs-extra:fs-extra 添加了本机 fs 模块中不包含的文件系统方法,fs 的替代品

4. 发布至 npm

添加打包命令

{
  "scripts": {
    "build": "tsc"
  },
}

package.json 增加配置。name description keywords author 这些自行修改就行

{
  "bin": {
    "node-cli": "./bin/index.js" // key 指的是 cli 运行名称
  },
  "files": [ // 只有这些文件才会发布到 npm
    "dist",
    "bin"
  ],
  "publishConfig": { // 发布的地址
    "access": "public",
    "registry": "https://registry.npmjs.org"
  }
}

修改 tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "sourceMap": true,
    "declaration": true,
    "strict": true,
    "skipLibCheck": true,
    "importHelpers": false,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "removeComments": false,
    "noUnusedLocals": true,
    "noImplicitAny": false,
    "noImplicitThis": false,
    "strictNullChecks": false,
    "resolveJsonModule": true,
    "outDir": "./dist",
    "baseUrl": "./src",
    "lib": ["esnext", "dom", "dom.iterable", "scripthost"]
  },
  "include": [
    "bin/index.js",
    "src/*.d.ts",
    "src/**/*.ts"
  ],
  "exclude": ["node_modules/**"]
}

发布 cli

pnpm build
npm publish

5. 总结

CLI 开发本身并不难,挑战在于合理利用第三方工具,以及根据公司业务需求进行开发。 比如我们可以开发工具有:

  • 项目模版初始化。
  • 根据后端 API 文档生成 request、类型定义文件。
  • 组件模版生成器
  • 本地自动部署
转载自:https://juejin.cn/post/7358381923922608154
评论
请登录