Monorepo+NestJSで共通コードを自動リロード

Monorepo+NestJSで共通コードを自動リロード

Turborepoを用いてモノレポ構成で開発していて、NestJSのホットリロード少しハマった。

下記のようなディレクトリ構成で共通コードをNestJSとNextJSで共有していた。

.
├── apps/
│   ├── frontend/
│   └── backend/
│       └── package.json
└── packages/
    └── shared/
        └── src/
            ├── hello.ts
            ├── index.ts
            ├── tsconfig.json
            └── package.json

共通コードは、tscでコンパイルし、開発時は--watchを付けてコードの変更を監視させる。

{
  "name": "@app/shared",
  "version": "0.0.1",
  "private": true,
  "files": [
    "dist"
  ],
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "tsc -b",
    "dev": "tsc -b --watch",
  },
  "devDependencies": {
    "typescript": "^5.9.3"
  }
}
{
  "compilerOptions": {
    "target": "ES2024",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "esModuleInterop": true,
    "isolatedModules": true,
    "declaration": true,
    "declarationMap": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": false,
    "emitDeclarationOnly": false,
    "baseUrl": ".",
    "outDir": "./dist",
    "rootDir": "./src",
    "composite": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

バックエンド側のNestJSには、下記のような感じで共通コードを依存関係として追加する。

{
  "name": "backend",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "dev": "nest start --watch --exec 'node --watch'"
  },
  "dependencies": {
    "@app/shared": "workspace:*",
  }
}

NestJS側で、--exec 'node --watch'を追記することで、import/requireしている共通コードが変更されるたびに自動的に再起動されるようになるとのこと。

https://github.com/vercel/turborepo/issues/8317#issuecomment-3469631371

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です