为你的 Monorepo 创建 TypeScript CLI

2025-06-07

为你的 Monorepo 创建 TypeScript CLI

我喜欢为我的 Monorepo 创建本地 CLI,以自动执行诸如build和 之类的任务deploy。这些任务通常需要的不仅仅是在 npm 脚本中链接几个命令(例如rimraf dist && tsc)。

使用commander.jstsx,我们可以创建用 TypeScript 编写的可执行程序,这些程序可以像任何其他 CLI 工具一样从命令行运行。

#!/usr/bin/env -S pnpm tsx
import { Command } from 'commander';

const program = new Command()
  .name('monorepo')
  .description('CLI for Monorepo')
  .version('1.0.0');

program
  .command('build')
  .description('Build the monorepo')
  .action(async () => {
    console.log('Building...');
    // run your build steps ...
  });

program
  .command('deploy')
  .description('Deploy the monorepo')
  .action(async () => {
    console.log('Deploying...');
    // run your deploy steps ...
  });

await program.parseAsync(process.argv);
Enter fullscreen mode Exit fullscreen mode

将此脚本另存为cli(或任何你喜欢的名称)到你的项目根目录中,并使用 使其可执行chmod +x cli。然后你可以使用 直接运行它./cli

$ ./cli
Usage: monorepo [options] [command]

CLI for Monorepo

Options:
  -V, --version   output the version number
  -h, --help      display help for command

Commands:
  build           Build the monorepo
  deploy          Deploy the monorepo
  help [command]  display help for command
Enter fullscreen mode Exit fullscreen mode

node让你无需、npx甚至无需扩展即可运行此程序的魔力.ts就在第一行 - shebang:

#!/usr/bin/env -S pnpm tsx
Enter fullscreen mode Exit fullscreen mode

这个脚本会告诉你的 shell 哪个程序应该执行这个文件。它会在后台将你的./cli命令翻译成pnpm tsx cli。这也适用于其他包管理器——你可以使用npmyarn代替pnpm

文章来源:https://dev.to/zirkelc/creating-a-typescript-cli-for-your-monorepo-5aa
PREV
我尝试在 1000 个公共 GitHub 存储库中查找 MongoDB 连接字符串
NEXT
React 中的 useRef() 钩子!