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
| #!/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 () => { 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); }
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) );
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);
|