>我想跟进我以前的有关打字稿cli的文章。我要继续进行以下操作:我计划实现构建命令以构建vite应用程序和deploy命令,以将应用程序部署到amazon s3和aws cloudfront。
#!/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(
[
/**
* Build tasks
*/
{
enabled: (ctx) => ctx.command === 'build' || ctx.command === 'deploy',
title: 'Build',
task: (ctx, task): Listr =>
task.newListr([
/**
* Runs `vite build`.
*/
{
title: `Run ${chalk.magenta('vite build')}`,
task: async (ctx, task): Promise => {
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([
/**
* Runs `aws s3 sync`.
*/
{
title: `Run ${chalk.magenta('aws s3 sync')}`,
task: async (ctx, task): Promise => {
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 => {
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);
任务分为构建任务和部署任务。由于部署需要一个构建步骤,因此我们使用启用属性来有条件地启用基于cli命令构建或部署的任务。每个任务都执行相应的cli命令并将其输出输出到控制台。 >将此脚本保存为cli.ts,并使用pnpm tsx cli运行:











