>웹 프론트엔드 >JS 튜토리얼 >TypeScript CLI: 스크립트 빌드 및 배포 자동화

TypeScript CLI: 스크립트 빌드 및 배포 자동화

Mary-Kate Olsen
Mary-Kate Olsen원래의
2025-01-27 20:31:20215검색

TypeScript CLI에 대한 이전 게시물에 대한 후속 조치를 취하고 싶습니다. 진행 방법은 다음과 같습니다. Vite 앱을 빌드하는 build 명령과 Amazon S3 및 AWS CloudFront에 앱을 배포하는 배포 명령을 구현할 계획입니다.

TypeScript CLI: 스크립트 빌드 및 배포 자동화

Monorepo용 TypeScript CLI 생성

크리스 쿡 ・ 2024년 12월 1일

#타입스크립트 #자바스크립트 #웹개발 #프로그램 작성

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>

작업은 빌드 작업과 배포 작업으로 구분됩니다. 배포에는 빌드 단계가 필요하므로 활성화된 속성을 사용하여 CLI 명령 빌드 또는 배포를 기반으로 작업을 조건부로 활성화합니다. 각 작업은 해당 CLI 명령을 실행하고 해당 출력을 콘솔에 파이프합니다.

이 스크립트를 cli.ts로 저장하고 pnpm tsx cli로 실행하세요.

TypeScript CLI: 스크립트 빌드 및 배포 자동화

위 내용은 TypeScript CLI: 스크립트 빌드 및 배포 자동화의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.