performance2025-03-08·9 min·157/348

Vercel 빌드 시간 최적화 방법

Vercel 빌드 시간을 줄여 배포 속도를 향상시키는 최적화 방법을 알아봅니다.

Vercel 빌드 시간 최적화 방법

Introduction

빌드 시간이 길어지면 배포 속도가 느려지고 개발자의 생산성이 떨어집니다. Vercel 빌드 시간을 최적화하는 방법을 알아보겠습니다.

Environment

  • Vercel 프로젝트 (Next.js 14+)
  • Turborepo (monorepo)
  • Node.js 18+
  • npm/yarn

Problem

빌드 시간이 너무 길어지는 문제:

Build completed in 45.23s
otal time: 45.23s

> Build error occurred
Error: Build exceeded maximum allowed duration

Analysis

빌드 시간에 영향을 미치는 요소:

  1. 의존성 설치 시간: node_modules 설치
  2. 컴파일 시간: TypeScript 컴파일
  3. 트랜스파일링: Next.js 트랜스파일링
  4. 정적 페이지 생성: getStaticProps 실행

Solution

1. 의존성 설치 최적화

// package.json
{
  "scripts": {
    "vercel-install": "npm ci --prefer-offline"
  }
}
# lock 파일 캐시 활용
npm ci --cache .npm-cache

# 동시 설치
npm ci --prefer-offline --no-audit --no-fund

2. Turborepo 캐시 설정

// turbo.json
{
  "$schema": "https://turbo.build/schema.json",
  "pipeline": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": [".next/**", "!.next/cache/**"],
      "inputs": ["src/**", "public/**", "next.config.js", "tsconfig.json"]
    },
    "lint": {
      "outputs": []
    }
  }
}

3. 불필요한 빌드 제외

// next.config.js
module.exports = {
  output: 'standalone',
  experimental: {
    optimizePackageImports: ['@mui/icons-material', '@mui/material'],
  },
  // 불필요한 페이지 제외
  exportPathMap: async function () {
    return {
      '/': { page: '/' },
      '/about': { page: '/about' },
    };
  },
};

4. TypeScript 컴파일 최적화

// tsconfig.json
{
  "compilerOptions": {
    "skipLibCheck": true,
    "incremental": true,
    "tsBuildInfoFile": ".tsbuildinfo"
  }
}

5. 이미지 최적화

// next.config.js
module.exports = {
  images: {
    unoptimized: true, // 빌드 시 이미지 최적화 비활성화
    formats: ['image/webp'],
  },
};

6. 빌드 분석

# 빌드 시간 분석
NEXT_TELEMETRY_DISABLED=1 vercel build --debug

# 번들 분석
npx @next/bundle-analyzer

7. 병렬 빌드 설정

# .github/workflows/parallel-build.yml
name: Parallel Build
on:
  push:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        package: [web, admin, docs]
    steps:
      - uses: actions/checkout@v4
      
      - name: Build ${{ matrix.package }}
        run: |
          cd packages/${{ matrix.package }}
          npm ci
          npm run build

8. 빌드 결과물 캐싱

// scripts/cache-build.js
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

function calculateCacheKey() {
  const files = [
    'package.json',
    'package-lock.json',
    'next.config.js',
    'tsconfig.json',
  ];
  
  const content = files
    .map(file => {
      try {
        return fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
      } catch {
        return '';
      }
    })
    .join('');
  
  return crypto.createHash('md5').update(content).digest('hex');
}

// 캐시 키 저장
const cacheKey = calculateCacheKey();
fs.writeFileSync('.build-cache-key', cacheKey);
console.log('Build cache key:', cacheKey);

9. Vercel 빌드 설정

// vercel.json
{
  "buildCommand": "npm run build",
  "installCommand": "npm ci --prefer-offline --no-audit --no-fund",
  "outputDirectory": ".next",
  "framework": "nextjs",
  "regions": ["iad1"]
}

Lessons Learned

  1. 캐시 활용: 빌드 캐시를 적극적으로 활용하면 빌드 시간을 크게 줄일 수 있습니다.
  2. 불필요한 작업 제거: 빌드 과정에서 불필요한 작업을 제거하면 속도가 향상됩니다.
  3. 병렬 처리: 독립적인 빌드 작업은 병렬로 실행하면 시간을 절약할 수 있습니다.
  4. 모니터링: 빌드 시간을 지속적으로 모니터링하여 병목 구간을 찾아야 합니다.
  5. 점진적 개선: 빌드 시간 최적화는 지속적인 개선 과정입니다.

This blog does not accept any external sponsorships, affiliate marketing, or ad revenue.