>  기사  >  웹 프론트엔드  >  패키지 관리자 이해: pnpm vs npm vs Yarn

패키지 관리자 이해: pnpm vs npm vs Yarn

PHPz
PHPz원래의
2024-08-09 01:00:22985검색

Understanding Package Managers: pnpm vs npm vs yarn

패키지 관리자 이해: pnpm vs npm vs Yarn

패키지 관리자는 JavaScript 생태계에서 프로젝트 종속성을 설치, 업데이트, 구성 및 제거하는 프로세스를 자동화하는 중요한 도구라는 사실을 지금쯤 알고 계실 것입니다. 세 가지 인기 패키지 관리자인 pnpm, npm, Yarn을 심층적으로 비교하여 내부 작동 방식, 주요 기능, 개발자를 위한 실질적인 의미를 설명하겠습니다.

먼저, 이 패키지 관리자는 동일한 기능을 가지고 있지만 접근 방식이 다르다는 점을 알아야 합니다. 그리고 우리는 그것들을 살펴볼 것입니다.

npm(노드 패키지 관리자)

먼저 NPM(Node Package Manager)에 대해 이야기해 보겠습니다. 이 패키지 관리자는 Node.js의 기본 패키지 관리자입니다. Node.js는 브라우저 외부의 서버 측에서 JavaScript 코드를 실행할 수 있는 런타임 환경입니다. npm을 시작하면서 거의 모든 초보자와 학습자가 npm에 대해 배웠기 때문에 여러분 모두 npm을 알고 계실 것입니다. 또한 NPM을 사용하면 package.json 파일에 정의된 맞춤 스크립트를 통해 테스트 실행, 프로젝트 빌드, 코드 배포와 같은 작업을 자동화할 수 있습니다. 특히 Node.js 개발을 위한 JavaScript 생태계의 필수 도구로, 재사용 가능한 코드를 더 쉽게 관리하고 공유할 수 있습니다.

npm 작동 방식:

  1. 종속성 해결:
- npm reads the `package.json` file to determine project dependencies.

- It constructs a dependency graph, resolving version conflicts using a deterministic algorithm.
  1. 설치:
- npm installs packages in a nested structure within the `node_modules` folder.

- Example structure:
    ```
    Copy
    ```
    `node_modules/ ├── package-a/ │ └── node_modules/ │ └── package-b/ └── package-c/`
  1. 평면 구조:
- npm v3+ attempts to flatten the dependency tree to reduce duplication.

- This can lead to "dependency hell" where different versions of the same package are required.
  1. 패키지 잠금:
- Uses `package-lock.json` to ensure consistent installs across environments.

- Contains the exact version of each package in the dependency tree.
  1. 스크립트:
- Allows defining custom scripts in `package.json`.

- Example:
    ```
    json
    ```
    Copy

    `"scripts": { "start": "node server.js", "test": "jest" }`

장점:

  • 150만 개 이상의 패키지를 보유한 최대 패키지 생태계

  • Node.js 내장

  • 광범위한 문서 및 커뮤니티 지원

단점:

  • yarn 및 pnpm에 비해 설치 속도가 느림

  • 큰 node_modules 폴더로 이어질 수 있음(농담으로 'node_modules 블랙홀'이라고도 함)

  • 종속성 충돌 가능성

방사

Yarn은 NPM의 대안으로 Facebook이 다른 회사와 협력하여 개발한 JavaScript용 패키지 관리자입니다. JavaScript 프로젝트에서 종속성 관리의 속도, 안정성 및 보안을 향상시키는 것을 목표로 합니다. Yarn은 캐시를 사용하여 다운로드한 패키지를 로컬에 저장하여 후속 설치 속도를 높임으로써 성능을 향상시킵니다. 또한 프로젝트에 사용되는 종속성의 정확한 버전을 잠그는 Yarn.lock 파일을 생성하여 여러 설정 간의 불일치를 방지함으로써 환경 전반에 걸쳐 일관성을 보장합니다. 또한 Yarn은 다운로드한 패키지의 무결성을 확인하여 더 나은 오프라인 지원, 더 예측 가능하고 결정적인 설치, 향상된 보안을 제공합니다. 이러한 기능으로 인해 Yarn은 특히 규모가 크거나 복잡한 JavaScript 프로젝트에서 프로젝트 종속성을 관리하는 데 널리 사용됩니다.

원사의 작동 방식:

  1. 종속성 해결:
- Like npm, yarn uses `package.json` for dependency information.

- Implements a more sophisticated resolution algorithm to handle complex dependency graphs.
  1. 병렬 설치:
- Installs packages in parallel, significantly improving speed.

- Uses a global cache to store downloaded packages, reducing network usage.
  1. 오프라인 모드:
- Caches packages for offline use.

- Can install dependencies without an internet connection if they're in the cache.
  1. 확정적 설치:
- Uses `yarn.lock` for consistent installations across different machines.

- Ensures that the same dependencies are installed regardless of install order.
  1. 작업 공간:
- Supports monorepo structures with workspaces.

- Example `package.json` for a workspace:
    ```
    json
    ```
    Copy

    `{ "private": true, "workspaces": ["packages/*"] }`

장점:

  • npm보다 빠르며, 특히 대규모 프로젝트의 경우

  • 안정적이고 일관된 설치

  • 강화된 보안 기능(체크섬 확인)

단점:

  • 여전히 대규모 node_modules 폴더가 생성됩니다

  • 일부 기능에는 Yarn 관련 명령을 사용해야 합니다

pnpm

pnpm은 NPM 및 Yarn을 대체하는 빠르고 디스크 공간 효율적인 JavaScript용 패키지 관리자입니다. 여러 프로젝트에 걸쳐 종속성을 복제하는 대신 컴퓨터에 단일 패키지 저장소를 생성하여 성능을 향상시키고 디스크 공간을 절약하도록 설계되었습니다. pnpm으로 패키지를 설치하면 공유 저장소에 대한 하드 링크가 생성되어 설치 프로세스가 더 빨라지고 사용되는 전체 디스크 공간이 줄어듭니다.

pnpm also ensures that dependencies are strictly isolated, which can prevent potential conflicts and issues in your projects. This strictness helps maintain consistency and reliability, particularly in complex projects with many dependencies. Additionally, pnpm supports features like workspaces, allowing you to manage multiple related projects within a single repository. Its efficiency and focus on performance make pnpm an attractive choice for developers looking to optimize their development workflow.

How pnpm works:

  1. Content-Addressable Storage:
- Stores all packages in a global store, typically located in `~/.pnpm-store`.

- Each project links to this store instead of having its own copy of packages.
  1. Symlinks:
- Uses symlinks to create a nested `node_modules` structure.

- Example structure:
    ```
    Copy
    ```
    `node_modules/ ├── .pnpm/ │ ├── package-a@1.0.0/ │ └── package-b@2.0.0/ ├── package-a -> .pnpm/package-a@1.0.0/node_modules/package-a └── package-b -> .pnpm/package-b@2.0.0/node_modules/package-b`
  1. Efficient Storage:
- Only one copy of a module version is saved on disk, regardless of how many projects use it.

- This can save gigabytes of disk space for large projects or multiple projects on the same machine.
  1. Strict Mode:
- Prevents packages from accessing arbitrary packages in the `node_modules` folder.

- Ensures that only declared dependencies are accessible, improving security and preventing "phantom dependencies".
  1. Monorepo Support:
- Native support for monorepos without additional tools.

- Example `pnpm-workspace.yaml`:
    ```
    yaml
    ```
    Copy

    `packages: - 'packages/*'`

Pros:

  • Dramatically saves disk space

  • Fast installation and updates

  • Ensures package isolation and prevents phantom dependencies

  • Built-in monorepo support

Cons:

  • Less widely adopted compared to npm and yarn

  • May have compatibility issues with some tools expecting a traditional node_modules structure

  • Learning curve for developers used to npm or yarn

Comparison Summary

  1. Installation Speed:
- pnpm > yarn > npm

- pnpm and yarn are significantly faster than npm, especially for larger projects.
  1. Disk Space Usage:
- pnpm > yarn ≈ npm

- pnpm can save up to 80% disk space compared to npm for projects with many dependencies.
  1. Ecosystem & Adoption:
- npm > yarn > pnpm

- npm has the largest ecosystem, but yarn and pnpm are gaining popularity.
  1. Dependency Resolution:
- All three use similar algorithms, but pnpm's approach is unique and more efficient.
  1. Lock File:
- All use lock files for consistency (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`)

- Lock files ensure reproducible builds across different environments.
  1. Monorepo Support:
- pnpm > yarn > npm

- pnpm and yarn have built-in support for monorepos, while npm requires additional tools.
  1. Security:
- pnpm > yarn > npm

- pnpm's strict mode and yarn's checksum verification provide additional security layers.

Practical Implications

  1. Project Onboarding:
- npm is often the easiest for new developers due to its ubiquity.

- pnpm and yarn may require additional setup but can significantly improve project efficiency.
  1. CI/CD Performance:
- pnpm and yarn can dramatically reduce build times in CI/CD pipelines due to their faster installation and caching mechanisms.
  1. Disk Space in Docker:
- Using pnpm can significantly reduce Docker image sizes for Node.js applications.
  1. Large-Scale Development:
- For large projects or organizations working on multiple projects, pnpm's space-saving feature can be a game-changer.
  1. Monorepo Management:
- pnpm and yarn are better suited for managing monorepos without additional tools.<br>




My Take

While a lot of you uses npm and yarn. Me and a lot of developers is moving to pnpm. The main reason is not only that its fast, but it also does not eat a lot of your storage. For me, that is the very main thing why I started using pnpm. If you think different than I am, please comment down bellow. Let me know what you guys think.

위 내용은 패키지 관리자 이해: pnpm vs npm vs Yarn의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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