[Nx] 패키지 베이스 모노레포 튜토리얼(Package-Based Monorepo)

Jeris·2023년 7월 27일
0

Nx docs translation

목록 보기
4/6

Example repository

새 워크스페이스 만들기

먼저 새 작업 공간을 만듭니다. 다음 명령을 사용하여 설정할 수 있습니다.

npx create-nx-workspace@latest package-based --preset=npm

파일 구조는 다음과 같아야 합니다:

package-based/
├── packages/
├── nx.json
└── package.json

패키지 만들기

패키지 폴더는 모노레포 라이브러리를 호스팅하는 곳입니다. 다음 구조의 새 is-even 폴더를 만듭니다:

package-based/
├── packages/
│   └── is-even/
│       ├── index.ts
│       └── package.json
├── nx.json
└── package.json

파일 내용을 다음과 일치하도록 업데이트합니다:


// package/is-even/index.ts 
export const isEven = (x: number) => x % 2 === 0;
// packages/is-even/package.json
{
  "name": "is-even",
  "version": "0.0.0",
  "main": "dist/index.js",
  "devDependencies": {},
  "scripts": {
    "build": "tsc index.ts --outDir dist"
  }
}

다음으로 TypeScript를 설치합니다(위의 package.json에서 빌드 스크립트에 tsc를 사용하고 있음을 알 수 있습니다). 패키지 수준에서 TypeScript를 설치할 수도 있지만, 전체 모노레포에 대해 전역적으로 설치하는 것이 더 편리합니다. 워크스페이스의 루트에서 다음 명령을 실행합니다.

npm i typescript -D -W

스크립트를 다음과 같이 빌드하세요:

npx nx build is-even

이제 빌드한 패키지가 예상대로 packages/is-even/dist 디렉토리에 존재합니다.

패키지 로컬 연결

패키지 기반 모노레포 스타일로 로컬에서 패키지를 연결하는 것은 NPM/Yarn/PNPM 워크스페이스를 사용하여 수행됩니다. 이 특정 설정에서는 NPM 워크스페이스를 사용합니다(워크스페이스 루트에 있는 package.json 파일의 workspaces 속성 참조).

패키지를 로컬로 연결하는 방법을 설명하기 위해 is-odd라는 다른 패키지를 만들어 보겠습니다. 기존 is-even 패키지를 복사할 수 있습니다:

package-based/
├── packages/
│   ├── is-even/
│   │   ├── index.ts
│   │   └── package.json
│   └── is-odd/
│       ├── index.ts
│       └── package.json
├── nx.json
└── package.json

파일의 콘텐츠는 다음과 같이 구성되어야 합니다:

// packages/is-odd/index.ts
import { isEven } from 'is-even';

export const isOdd = (x: number) => !isEven(x);
// packages/is-odd/package.json
{
  "name": "is-odd",
  "version": "0.0.0",
  "main": "dist/index.js",
  "devDependencies": {},
  "scripts": {
    "build": "tsc index.ts --outDir dist"
  },
  "dependencies": {
    "is-even": "*"
  }
}

is-oddis-even 패키지에서 isEven 함수를 가져옵니다. 따라서 package.json 파일에 is-even 패키지가 종속성으로 나열되어야 합니다.

루트 레벨 package.jsonworkspaces 속성은 NPM이 packages 디렉토리에 있는 모든 패키지에 대한 링크를 생성하도록 지시합니다. 이렇게 하면 패키지를 NPM 레지스트리에 먼저 게시할 필요가 없습니다. (Yarn 및 PNPM 워크스페이스에도 비슷한 기능이 있습니다.)

워크스페이스 실행의 루트에서 다음을 실행하세요:

npm install

NPM은 파일 시스템에 다음과 같은 심볼릭 링크를 생성합니다: node_modules/is-even, node_modules/is-odd, 그래서 패키지가 변경될 때마다 packages/is-evenpackages/is-odd 디렉토리들에 변경 사항을 반영합니다.

태스크 종속성

대부분의 모노레포들은 서로 다른 패키지뿐만 아니라 해당 태스크 간에도 종속성이 있습니다.

예를 들어, is-odd를 빌드할 때마다 is-even이 미리 빌드되었는지 확인해야 합니다. Nx는 nx.jsontargetDefaults 속성을 추가하여 이러한 태스크 종속성을 정의할 수 있습니다.

// nx.json
{
  ...
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"]
    }
  }
}

이렇게 하면 패키지 자체의 빌드 타겟이 실행되기 전에 모든 종속 프로젝트의 빌드 타겟을 먼저 실행하도록 Nx에 지시합니다.

기존 dist 폴더를 모두 제거하고 다음 명령을 실행합니다:

npx nx build is-odd

자동으로 먼저 is-even 패키지에 대한 빌드를 실행한 다음 is-odd 패키지에 대한 빌드를 실행합니다. is-even이 이전에 빌드된 적이 있는 경우 캐시에서 복원됩니다.

캐시 빌드 결과

다음 명령을 실행합니다:

npx nx build is-even

> nx run is-even:build  [existing outputs match the cache, left as is]


> is-even@0.0.0 build
> tsc index.ts --outDir dist


 ——————————————————————————————————————————————————————————————————————————————————————————

 >  NX   Successfully ran target build for project is-even (33ms)

   Nx read the output from the cache instead of running the command for 1 out of 1 tasks.

앞서 이 튜토리얼에서 빌드 스크립트를 실행했을 때 빌드 스크립트의 캐시가 이미 채워져 있었습니다.

여러 태스크들 실행

워크스페이스에 모든 패키지에 대해 빌드 대상을 실행하려면 다음 명령을 사용합니다:

npx nx run-many -t build

    ✔  nx run is-even:build  [existing outputs match the cache, left as is]
    ✔  nx run is-odd:build  [existing outputs match the cache, left as is]

 ————————————————————————————————————————————————————————————————————————————————————————

 >  NX   Successfully ran target build for 2 projects (35ms)

   Nx read the output from the cache instead of running the command for 2 out of 2 tasks.

두 빌드 모두 캐시에서 재생됩니다. --skip-nx-cache 옵션을 추가하여 캐시를 건너뛸 수 있습니다:

npx nx run-many -t build --skip-nx-cache

    ✔  nx run is-even:build (1s)
    ✔  nx run is-odd:build (1s)

 ———————————————————————————————————————————————————————————————————————

 >  NX   Successfully ran target build for 2 projects (2s)

이 메서드를 사용하면 is-even 빌드가 is-odd 빌드보다 먼저 실행되고 is-even 빌드가 한 번만 발생한다는 것을 알 수 있습니다. 이것은 run-many가 앞서 설정한 targetDefaults에 의해 어떻게 정보를 받는지 보여줍니다.

또한 이 명령을 사용하여 변경된 패키지에 대해서만 작업을 실행할 수 있습니다:

npx nx affected -t build


 >  NX   Affected criteria defaulted to --base=main --head=HEAD


    ✔  nx run is-even:build  [existing outputs match the cache, left as is]
    ✔  nx run is-odd:build  [existing outputs match the cache, left as is]

 ——————————————————————————————————————————————————————————————————————————————————————————————

 >  NX   Successfully ran target build for 2 projects (34ms)

   Nx read the output from the cache instead of running the command for 2 out of 2 tasks.

base, head 옵션이 기본값으로 채워진 것을 확인할 수 있습니다. 필요에 따라 여기에 고유한 옵션을 제공할 수 있습니다. 캐시가 영향을 받는 명령과 함께 사용된다는 점도 주목하세요.

더보기

Core Features
Mental Model
Adopting Nx
Integrated Repos vs Package-Based Repos

Reference

profile
job's done

0개의 댓글