
我喜欢为我的 monorepo 创建本地 cli,以自动执行构建和部署等任务。这些任务通常需要的不仅仅是在 npm 脚本中链接几个命令(如 rimraf dist && tsc)。
使用 commander.js 和 tsx,我们可以创建用 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);
将此脚本保存为项目根目录中的 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
允许您在没有节点、npx 甚至 .ts 扩展名的情况下运行它的魔力就在第一行 - shebang:
#!/usr/bin/env -S pnpm tsx
这个 shebang 告诉你的 shell 哪个程序应该执行这个文件。在幕后,它将您的 ./cli 命令转换为 pnpm tsx cli。这也适用于其他包管理器 - 您可以使用 npm 或yarn 代替 pnpm。
以上就是为您的 Monorepo 创建 TypeScript CLI的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号