使用TypeScript编写nodejs命令行工具

使用 TypeScript 开发全局 Node.js 命令行程序

下面我将展示如何创建一个完整的全局 Node.js 命令行工具,使用 TypeScript 编写,并通过 npm 实现全局安装和运行。

完整实现方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// src/cli.ts
#!/usr/bin/env node

import { Command } from 'commander';
import chalk from 'chalk';
import figlet from 'figlet';
import gradient from 'gradient-string';
import inquirer from 'inquirer';
import fs from 'fs';
import path from 'path';

// 定义项目信息接口
interface ProjectInfo {
name: string;
version: string;
author: string;
license: string;
}

// 创建命令行程序
const program = new Command();

// 设置基本信息
program
.name('ts-cli-tool')
.description(chalk.cyan('一个强大的 TypeScript 命令行工具'))
.version('1.0.0', '-v, --version', '显示版本信息');

// 添加欢迎命令
program
.command('welcome')
.description('显示欢迎信息')
.action(() => {
console.log(
gradient.rainbow(
figlet.textSync('TS CLI Tool', {
horizontalLayout: 'full',
verticalLayout: 'default',
width: 80,
whitespaceBreak: true,
})
)
);
console.log(chalk.cyanBright('欢迎使用 TypeScript 命令行工具!'));
console.log(chalk.yellow('这是一个功能强大的命令行工具,使用 TypeScript 开发,支持全局安装运行。'));
});

// 添加项目初始化命令
program
.command('init')
.description('初始化一个新项目')
.action(async () => {
// 使用 inquirer 收集用户输入
const answers = await inquirer.prompt([
{
type: 'input',
name: 'name',
message: '项目名称:',
default: 'my-project',
},
{
type: 'input',
name: 'version',
message: '版本号:',
default: '1.0.0',
},
{
type: 'input',
name: 'author',
message: '作者:',
default: '',
},
{
type: 'list',
name: 'license',
message: '选择许可证:',
choices: ['MIT', 'Apache-2.0', 'GPL-3.0', 'BSD-2-Clause', 'BSD-3-Clause', 'Unlicense'],
default: 'MIT',
},
]);

// 创建项目信息对象
const projectInfo: ProjectInfo = {
name: answers.name,
version: answers.version,
author: answers.author,
license: answers.license,
};

// 创建项目目录
const projectDir = path.join(process.cwd(), projectInfo.name);
if (!fs.existsSync(projectDir)) {
fs.mkdirSync(projectDir);
}

// 创建 package.json
const packageJson = {
name: projectInfo.name,
version: projectInfo.version,
description: "",
main: "dist/index.js",
scripts: {
build: "tsc",
start: "node dist/index.js",
test: "echo \"Error: no test specified\" && exit 1"
},
author: projectInfo.author,
license: projectInfo.license,
devDependencies: {
"typescript": "^5.0.0"
}
};

fs.writeFileSync(
path.join(projectDir, 'package.json'),
JSON.stringify(packageJson, null, 2)
);

// 创建 tsconfig.json
const tsConfig = {
compilerOptions: {
target: "es6",
module: "commonjs",
outDir: "dist",
rootDir: "src",
strict: true,
esModuleInterop: true,
skipLibCheck: true,
forceConsistentCasingInFileNames: true
},
include: ["src/**/*"]
};

fs.writeFileSync(
path.join(projectDir, 'tsconfig.json'),
JSON.stringify(tsConfig, null, 2)
);

// 创建源目录和示例文件
const srcDir = path.join(projectDir, 'src');
if (!fs.existsSync(srcDir)) {
fs.mkdirSync(srcDir);
}

const indexContent = `console.log("Hello from ${projectInfo.name}!");`;
fs.writeFileSync(
path.join(srcDir, 'index.ts'),
indexContent
);

// 显示成功消息
console.log(chalk.green(`\n✅ 项目 "${projectInfo.name}" 初始化成功!`));
console.log(chalk.yellow(`\n接下来可以执行以下命令:`));
console.log(chalk.cyan(` cd ${projectInfo.name}`));
console.log(chalk.cyan(` npm install`));
console.log(chalk.cyan(` npm run build`));
console.log(chalk.cyan(` npm start`));
});

// 添加文件操作命令
program
.command('list <directory>')
.description('列出目录内容')
.action((directory) => {
try {
const dirPath = path.resolve(directory);
if (!fs.existsSync(dirPath)) {
console.log(chalk.red(`错误:目录 "${dirPath}" 不存在`));
return;
}

console.log(chalk.blueBright(`\n目录内容: ${dirPath}\n`));

const items = fs.readdirSync(dirPath, { withFileTypes: true });
items.forEach(item => {
const type = item.isDirectory() ? '📁 目录' : '📄 文件';
const size = item.isFile()
? `(${Math.ceil(fs.statSync(path.join(dirPath, item.name)).size / 1024} KB)`
: '';
console.log(` ${type.padEnd(10)} ${chalk.green(item.name.padEnd(30))} ${size}`);
});

console.log(`\n共 ${items.length} 个项目`);
} catch (error) {
console.log(chalk.red(`错误: ${(error as Error).message}`));
}
});

// 添加帮助命令
program.addHelpText('after', `
${chalk.yellowBright('示例命令:')}
${chalk.cyan('ts-cli-tool welcome')} 显示欢迎信息
${chalk.cyan('ts-cli-tool init')} 初始化新项目
${chalk.cyan('ts-cli-tool list ./')} 列出当前目录内容
${chalk.cyan('ts-cli-tool help')} 显示帮助信息

${chalk.magentaBright('🌟 提示:')}
使用 ${chalk.cyan('--help')} 选项查看任何命令的详细信息
`);

// 处理未识别命令
program.on('command:*', () => {
console.log(chalk.red(`\n错误: 未知命令 '${program.args.join(' ')}'`));
console.log(`使用 ${chalk.cyan('--help')} 查看可用命令\n`);
process.exit(1);
});

// 解析命令行参数
program.parse(process.argv);

package.json 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
"name": "ts-cli-tool",
"version": "1.0.0",
"description": "一个使用TypeScript开发的全局命令行工具",
"main": "dist/cli.js",
"bin": {
"ts-cli-tool": "dist/cli.js"
},
"scripts": {
"build": "tsc",
"prepublishOnly": "npm run build",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": ["cli", "typescript", "command-line", "tools"],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"chalk": "^5.3.0",
"commander": "^12.0.0",
"figlet": "^1.7.0",
"gradient-string": "^3.0.0",
"inquirer": "^9.2.15"
},
"devDependencies": {
"@types/figlet": "^1.7.0",
"@types/inquirer": "^9.0.7",
"@types/node": "^20.11.5",
"typescript": "^5.3.3"
}
}

tsconfig.json 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}

开发与使用指南

1. 安装依赖

1
npm install

2. 编译 TypeScript 代码

1
npm run build

3. 本地测试安装

1
npm link

4. 使用命令行工具

1
2
3
4
5
6
7
8
# 显示欢迎信息
ts-cli-tool welcome

# 初始化新项目
ts-cli-tool init

# 列出当前目录内容
ts-cli-tool list ./

5. 发布到 npm(可选)

1
2
npm login
npm publish

6. 全局安装(用户端)

1
npm install -g ts-cli-tool

功能特点

  1. 完整的 TypeScript 支持:使用 TypeScript 编写,提供类型安全
  2. 丰富的交互体验
    • 彩色终端输出
    • ASCII 艺术字欢迎界面
    • 渐变色效果
  3. 实用功能
    • 项目初始化(创建 package.json、tsconfig.json 等)
    • 目录内容浏览
    • 交互式表单输入
  4. 全局安装支持
    • 通过 npm 全局安装后可在任何目录运行
  5. 用户友好帮助系统
    • 详细的命令帮助
    • 示例命令提示
    • 错误处理

项目结构

1
2
3
4
5
6
7
8
ts-cli-tool/
├── src/
│ └── cli.ts // 主入口文件
├── dist/ // 编译后的 JavaScript 文件
├── node_modules/
├── package.json // 项目配置
├── tsconfig.json // TypeScript 配置
└── README.md // 项目文档

这个示例展示了如何创建一个专业的 TypeScript 命令行工具,包含实际有用的功能,同时提供了丰富的用户界面和友好的交互体验。