mcpField
M
monorepo-management

monorepo-management

github.com/ovachiever開発5647 回インストール48 週間前に更新
リポジトリ

monorepo-management について

Monorepo Managementは、複数のパッケージやアプリを含むリポジトリの計画、運用、問題解決を支援するスキルです。ワークスペースやビルドツール、コード共有、性能、CI/CD、パッケージ公開を扱います。

主な機能

  1. 01ワークスペース設定とパッケージ管理
  2. 02TurborepoとNxのガイド
  3. 03コードと設定の共有パターン
  4. 04ビルドキャッシュとCI/CDの実践
  5. 05バージョン管理とパッケージ公開

活用シーン

  1. 01Monorepoの新規構築や移行
  2. 02Monorepoのビルド・テスト性能の改善
  3. 03変更対象プロジェクト向けCI/CDの設定
  4. 04共有依存関係とパッケージ公開の管理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/ovachiever/droid-tings --skill monorepo-management

インストール後、Claude Code で/monorepo-managementを入力して読み込まれたか確認します。

詳細

モノレポ管理

コード共有、一貫したツール、複数のパッケージやアプリケーションにまたがるアトミックな変更を実現する、効率的でスケーラブルなモノレポを構築します。

このスキルを使う場面

  • 新しいモノレポプロジェクトをセットアップする
  • マルチレポからモノレポへ移行する
  • ビルドとテストのパフォーマンスを最適化する
  • 共有依存関係を管理する
  • コード共有の戦略を実装する
  • モノレポ向けに CI/CD をセットアップする
  • パッケージのバージョン管理と公開を行う
  • モノレポ固有の問題をデバッグする

基本概念

1. モノレポを使う理由

メリット:

  • コードと依存関係を共有できる
  • プロジェクトをまたいだアトミックなコミットが可能
  • 一貫したツールと標準を使用できる
  • リファクタリングが容易
  • 依存関係の管理を簡素化できる
  • コードの可視性が向上する

課題:

  • 大規模環境でのビルドパフォーマンス
  • CI/CD の複雑さ
  • アクセス制御
  • 大規模な Git リポジトリ
2. モノレポツール

パッケージマネージャー:

  • pnpm workspaces(推奨)
  • npm workspaces
  • Yarn workspaces

ビルドシステム:

  • Turborepo(ほとんどのケースで推奨)
  • Nx(機能が豊富で複雑)
  • Lerna(古く、メンテナンスモード)

Turborepo のセットアップ

初期セットアップ
# Create new monorepo
npx create-turbo@latest my-monorepo
cd my-monorepo

# Structure:
# apps/
#   web/          - Next.js app
#   docs/         - Documentation site
# packages/
#   ui/           - Shared UI components
#   config/       - Shared configurations
#   tsconfig/     - Shared TypeScript configs
# turbo.json      - Turborepo configuration
# package.json    - Root package.json
設定
// turbo.json
{
  "$schema": "https://turbo.build/schema.json",
  "globalDependencies": ["**/.env.*local"],
  "pipeline": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**", ".next/**", "!.next/cache/**"]
    },
    "test": {
      "dependsOn": ["build"],
      "outputs": ["coverage/**"]
    },
    "lint": {
      "outputs": []
    },
    "dev": {
      "cache": false,
      "persistent": true
    },
    "type-check": {
      "dependsOn": ["^build"],
      "outputs": []
    }
  }
}
// package.json (root)
{
  "name": "my-monorepo",
  "private": true,
  "workspaces": [
    "apps/*",
    "packages/*"
  ],
  "scripts": {
    "build": "turbo run build",
    "dev": "turbo run dev",
    "test": "turbo run test",
    "lint": "turbo run lint",
    "format": "prettier --write \"**/*.{ts,tsx,md}\"",
    "clean": "turbo run clean && rm -rf node_modules"
  },
  "devDependencies": {
    "turbo": "^1.10.0",
    "prettier": "^3.0.0",
    "typescript": "^5.0.0"
  },
  "packageManager": "[email protected]"
}
パッケージ構成
// packages/ui/package.json
{
  "name": "@repo/ui",
  "version": "0.0.0",
  "private": true,
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "types": "./dist/index.d.ts"
    },
    "./button": {
      "import": "./dist/button.js",
      "types": "./dist/button.d.ts"
    }
  },
  "scripts": {
    "build": "tsup src/index.ts --format esm,cjs --dts",
    "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
    "lint": "eslint src/",
    "type-check": "tsc --noEmit"
  },
  "devDependencies": {
    "@repo/tsconfig": "workspace:*",
    "tsup": "^7.0.0",
    "typescript": "^5.0.0"
  },
  "dependencies": {
    "react": "^18.2.0"
  }
}

pnpm Workspaces

セットアップ
# pnpm-workspace.yaml
packages:
  - 'apps/*'
  - 'packages/*'
  - 'tools/*'
// .npmrc
# Hoist shared dependencies
shamefully-hoist=true

# Strict peer dependencies
auto-install-peers=true
strict-peer-dependencies=true

# Performance
store-dir=~/.pnpm-store
依存関係の管理
# Install dependency in specific package
pnpm add react --filter @repo/ui
pnpm add -D typescript --filter @repo/ui

# Install workspace dependency
pnpm add @repo/ui --filter web

# Install in all packages
pnpm add -D eslint -w

# Update all dependencies
pnpm update -r

# Remove dependency
pnpm remove react --filter @repo/ui
スクリプト
# Run script in specific package
pnpm --filter web dev
pnpm --filter @repo/ui build

# Run in all packages
pnpm -r build
pnpm -r test

# Run in parallel
pnpm -r --parallel dev

# Filter by pattern
pnpm --filter "@repo/*" build
pnpm --filter "...web" build  # Build web and dependencies

Nx モノレポ

セットアップ
# Create Nx monorepo
npx create-nx-workspace@latest my-org

# Generate applications
nx generate @nx/react:app my-app
nx generate @nx/next:app my-next-app

# Generate libraries
nx generate @nx/react:lib ui-components
nx generate @nx/js:lib utils
設定
// nx.json
{
  "extends": "nx/presets/npm.json",
  "$schema": "./node_modules/nx/schemas/nx-schema.json",
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production"],
      "cache": true
    },
    "test": {
      "inputs": ["default", "^production", "{workspaceRoot}/jest.preset.js"],
      "cache": true
    },
    "lint": {
      "inputs": ["default", "{workspaceRoot}/.eslintrc.json"],
      "cache": true
    }
  },
  "namedInputs": {
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": [
      "default",
      "!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)",
      "!{projectRoot}/tsconfig.spec.json"
    ],
    "sharedGlobals": []
  }
}
タスクの実行
# Run task for specific project
nx build my-app
nx test ui-components
nx lint utils

# Run for affected projects
nx affected:build
nx affected:test --base=main

# Visualize dependencies
nx graph

# Run in parallel
nx run-many --target=build --all --parallel=3

共有設定

TypeScript の設定
// packages/tsconfig/base.json
{
  "compilerOptions": {
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "incremental": true,
    "declaration": true
  },
  "exclude": ["node_modules"]
}

// packages/tsconfig/react.json
{
  "extends": "./base.json",
  "compilerOptions": {
    "jsx": "react-jsx",
    "lib": ["ES2022", "DOM", "DOM.Iterable"]
  }
}

// apps/web/tsconfig.json
{
  "extends": "@repo/tsconfig/react.json",
  "compilerOptions": {
    "outDir": "dist",
    "rootDir": "src"
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}
ESLint の設定
// packages/config/eslint-preset.js
module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
    'prettier',
  ],
  plugins: ['@typescript-eslint', 'react', 'react-hooks'],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 2022,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
  rules: {
    '@typescript-eslint/no-unused-vars': 'error',
    'react/react-in-jsx-scope': 'off',
  },
};

// apps/web/.eslintrc.js
module.exports = {
  extends: ['@repo/config/eslint-preset'],
  rules: {
    // App-specific rules
  },
};

コード共有のパターン

パターン 1:共有 UI コンポーネント
// packages/ui/src/button.tsx
import * as React from 'react';

export interface ButtonProps {
  variant?: 'primary' | 'secondary';
  children: React.ReactNode;
  onClick?: () => void;
}

export function Button({ variant = 'primary', children, onClick }: ButtonProps) {
  return (
    <button
      className={`btn btn-${variant}`}
      onClick={onClick}
    >
      {children}
    </button>
  );
}

// packages/ui/src/index.ts
export { Button, type ButtonProps } from './button';
export { Input, type InputProps } from './input';

// apps/web/src/app.tsx
import { Button } from '@repo/ui';

export function App() {
  return <Button variant="primary">Click me</Button>;
}
パターン 2:共有ユーティリティ
// packages/utils/src/string.ts
export function capitalize(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

export function truncate(str: string, length: number): string {
  return str.length > length ? str.slice(0, length) + '...' : str;
}

// packages/utils/src/index.ts
export * from './string';
export * from './array';
export * from './date';

// Usage in apps
import { capitalize, truncate } from '@repo/utils';
パターン 3:共有型
// packages/types/src/user.ts
export interface User {
  id: string;
  email: string;
  name: string;
  role: 'admin' | 'user';
}

export interface CreateUserInput {
  email: string;
  name: string;
  password: string;
}

// Used in both frontend and backend
import type { User, CreateUserInput } from '@repo/types';

ビルドの最適化

Turborepo のキャッシュ
// turbo.json
{
  "pipeline": {
    "build": {
      // Build depends on dependencies being built first
      "dependsOn": ["^build"],

      // Cache these outputs
      "outputs": ["dist/**", ".next/**"],

      // Cache based on these inputs (default: all files)
      "inputs": ["src/**/*.tsx", "src/**/*.ts", "package.json"]
    },
    "test": {
      // Run tests in parallel, don't depend on build
      "cache": true,
      "outputs": ["coverage/**"]
    }
  }
}
リモートキャッシュ
# Turborepo Remote Cache (Vercel)
npx turbo login
npx turbo link

# Custom remote cache
# turbo.json
{
  "remoteCache": {
    "signature": true,
    "enabled": true
  }
}

モノレポ向けの CI/CD

GitHub Actions
# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0  # For Nx affected commands

      - uses: pnpm/action-setup@v2
        with:
          version: 8

      - uses: actions/setup-node@v3
        with:
          node-version: 18
          cache: 'pnpm'

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Build
        run: pnpm turbo run build

      - name: Test
        run: pnpm turbo run test

      - name: Lint
        run: pnpm turbo run lint

      - name: Type check
        run: pnpm turbo run type-check
影響を受けるものだけをデプロイする
# Deploy only changed apps
- name: Deploy affected apps
  run: |
    if pnpm nx affected:apps --base=origin/main --head=HEAD | grep -q "web"; then
      echo "Deploying web app"
      pnpm --filter web deploy
    fi

ベストプラクティス

  1. 一貫したバージョン管理:ワークスペース全体で依存関係のバージョンを固定します
  2. 共有設定:ESLint、TypeScript、Prettier の設定を一元管理します
  3. 依存関係グラフ:循環依存を避け、非循環に保ちます
  4. 効果的なキャッシュ:入力と出力を正しく設定します
  5. 型安全性:フロントエンドとバックエンドで型を共有します
  6. テスト戦略:パッケージではユニットテスト、アプリでは E2E テストを実施します
  7. ドキュメント:各パッケージに README を用意します
  8. リリース戦略:バージョン管理に changesets を使用します

よくある落とし穴

  • 循環依存:A が B に依存し、B が A に依存する
  • ファントム依存関係:package.json に記載されていない依存関係を使用する
  • 不適切なキャッシュ入力:Turborepo の入力にファイルが不足している
  • 過剰な共有:分離すべきコードまで共有する
  • 共有不足:パッケージ間でコードを重複させる
  • 大規模なモノレポ:適切なツールがないとビルドが遅くなる

パッケージの公開

# Using Changesets
pnpm add -Dw @changesets/cli
pnpm changeset init

# Create changeset
pnpm changeset

# Version packages
pnpm changeset version

# Publish
pnpm changeset publish
# .github/workflows/release.yml
- name: Create Release Pull Request or Publish
  uses: changesets/action@v1
  with:
    publish: pnpm release
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

リソース

  • references/turborepo-guide.md:Turborepo の包括的なドキュメント
  • references/nx-guide.md:Nx モノレポのパターン
  • references/pnpm-workspaces.md:pnpm workspace の機能
  • assets/monorepo-checklist.md:セットアップチェックリスト
  • assets/migration-guide.md:マルチレポからモノレポへの移行
  • scripts/dependency-graph.ts:パッケージの依存関係を可視化する

コメント