TypeScript CLI に関する前回の投稿の続きを書きたいと思います。今後の進め方は次のとおりです。Vite アプリを構築する build コマンドと、アプリを Amazon S3 と AWS CloudFront にデプロイするdeploy コマンドを実装する予定です。
Listr2 をタスク ランナーとして使用し、アプリの構築とデプロイに必要な手順を定義します。 execa を使用して、Vite と AWS の CLI コマンドを実行します。 TypeScript コードを実行しているため、CLI コマンドの代わりにプログラム API を使用することもできますが、シンプルにしておきましょう!
#!/usr/bin/env -S pnpm tsx import chalk from 'chalk'; import { Command } from 'commander'; import { Listr } from 'listr2'; import { $ } from 'execa'; interface Ctx { command: 'build' | 'deploy'; } const tasks = new Listr<ctx>( [ /** * Build tasks */ { enabled: (ctx) => ctx.command === 'build' || ctx.command === 'deploy', title: 'Build', task: (ctx, task): Listr => task.newListr<ctx>([ /** * Runs `vite build`. */ { title: `Run ${chalk.magenta('vite build')}`, task: async (ctx, task): Promise<void> => { const cmd = $({ all: true })`vite build`; cmd.all.pipe(task.stdout()); await cmd; task.output = `Build completed: ${chalk.dim('./dist')}`; }, rendererOptions: { persistentOutput: true }, }, ]), }, /** * Deploy tasks */ { enabled: (ctx) => ctx.command === 'deploy', title: 'Deploy', task: (ctx, task): Listr => task.newListr<ctx>([ /** * Runs `aws s3 sync`. */ { title: `Run ${chalk.magenta('aws s3 sync')}`, task: async (ctx, task): Promise<void> => { const build = './dist'; const bucket = 's3://my-bucket'; const cmd = $({ all: true })`aws s3 sync ${build} ${bucket} --delete`; cmd.all.pipe(task.stdout()); await cmd; task.output = `S3 sync completed: ${chalk.dim(bucket)}`; }, rendererOptions: { persistentOutput: true }, }, /** * Runs `aws cloudfront create-invalidation`. */ { title: `Run ${chalk.magenta('aws cloudfront create-invalidation')}`, task: async (ctx, task): Promise<void> => { const distributionId = 'E1234567890ABC'; const cmd = $({ all: true })`aws cloudfront create-invalidation --distribution-id ${distributionId} --paths /* --no-cli-pager`; cmd.all.pipe(task.stdout()); await cmd; task.output = `CloudFront invalidation completed: ${chalk.dim(distributionId)}`; }, rendererOptions: { persistentOutput: true }, }, ]), }, ], { rendererOptions: { collapseSubtasks: false, }, }, ); const program = new Command() .name('monorepo') .description('CLI for Monorepo') .version('1.0.0'); program .command('build') .description('Build the monorepo') .action(async () => { await tasks.run({ command: 'build' }); }); program .command('deploy') .description('Deploy the monorepo') .action(async () => { await tasks.run({ command: 'deploy' }); }); await program.parseAsync(process.argv); </void></void></ctx></void></ctx></ctx>
タスクはビルド タスクとデプロイ タスクに分割されます。デプロイにはビルドステップが必要なため、enabled プロパティを使用して、CLI コマンドのビルドまたはデプロイに基づいてタスクを条件付きで有効にします。各タスクは対応する CLI コマンドを実行し、その出力をコンソールにパイプします。
このスクリプトを cli.ts として保存し、pnpm tsx cli で実行します。
以上がTypeScript CLI:ビルドと展開スクリプトを自動化しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。