Home > Web Front-end > JS Tutorial > body text

npm Peer Dependencies for the Professional Developer

Mary-Kate Olsen
Release: 2024-10-14 13:27:29
Original
720 people have browsed it

npm Peer Dependencies for the Professional Developer

이 기사에서는 npm 피어 종속성이 무엇인지, 특히 언제 사용해야 하는지 명확히 설명합니다. 피어 종속성은 프로젝트의 package.json 파일의 PeerDependency 개체에 나열됩니다.

이 기사를 최대한 활용하려면 최소한 npm에 대한 기본 지식이 있어야 합니다.

내용물

이 기사 내용:

  1. 피어 종속성이 일반 종속성과 어떻게 작동하는지 비교할 것입니다.
  2. 피어 종속성과 종속성의 몇 가지 를 살펴보겠습니다.
  3. 그런 다음 npm이 버전 충돌을 처리하는 방법을 살펴보겠습니다.
  4. 마지막으로 기본 사항을 확고하게 파악하여 동료 종속이 적절한 시기를 결정하는 접근 방식을 제시하겠습니다.

시나리오

실제로 Angular 또는 React 구성 요소 라이브러리를 생성하거나 일부 기능을 내보내는 간단한 JavaScript 파일을 생성한다고 가정해 보겠습니다.

귀하의 프로젝트는 npm 레지스트리의 패키지에 의존합니다. 이 패키지는 프로젝트의 종속성입니다.

프로젝트에서 자신만의 npm 패키지를 만들고 싶습니다. 따라서 npm pack을 사용하여 프로젝트에서 npm 패키지를 생성합니다. npm 레지스트리에 게시하기로 결정할 수도 있습니다.

다른 팀은 npm 레지스트리에서 패키지로 구성 요소 라이브러리를 찾을 수 있습니다. npm install을 사용하여 패키지를 자신의 프로젝트에 종속성으로 추가할 수 있습니다. package.json의 종속성피어 종속성을 사용하여 구성 요소 라이브러리가 작동하려면 어떤 패키지도 추가해야 하는지 다른 프로젝트에 알려줍니다.

종속성과 피어 종속성

가장 기본적인 수준에서 종속성동료 종속성이 작동하는 방식은 다음과 같습니다.

종속성

종속성은 종속성 개체의 프로젝트 package.json 파일에 나열됩니다.

코드의 종속성에 패키지를 추가하면 다음과 같이 됩니다.

  • 내 코드를 실행하려면 이 패키지가 필요합니다.
  • 이 패키지가 내 node_modules 디렉터리에 아직 없으면 자동으로 추가하세요.
  • 또한 이 패키지의 종속성에 나열된 모든 패키지를 추가하세요. 이러한 패키지를 전이적 종속성이라고 합니다.

피어 종속성

피어 종속성은 프로젝트의 package.json 파일에 있는 PeerDependency 개체에 나열됩니다.

코드의 PeerDependency에 패키지를 추가하면 다음과 같이 됩니다.

  • 내 코드가 이 버전의 패키지와 호환됩니다.
  • 이 패키지가 node_modules에 이미 존재하는 경우 아무 작업도 수행하지 마세요.
  • 이 패키지가 node_modules 디렉터리에 아직 존재하지 않거나 잘못된 버전인 경우 추가하지 마세요. 단, 찾을 수 없다는 경고를 사용자에게 표시합니다.

종속성 추가

그래서 npm 패키지 폴더의 package.json 파일에 종속성을 추가합니다. 패키지를 종속성으로 추가하는 방법과 패키지 종속성의 몇 가지 예를 정확히 살펴보겠습니다.

종속성 추가

종속성은 코드를 실행하기 위해 의존하는 npm 패키지입니다. 종속성으로 추가할 수 있는 인기 패키지로는 lodash, D3 및 Chartjs가 있습니다.

다음과 같은 일반 종속성을 추가합니다.

npm install lodash
Copy after login

npm은 프로젝트의 package.json 파일에 있는 종속 항목에 패키지 이름과 버전을 추가합니다.

"dependencies": {
  "lodash": "^4.17.11"
}
Copy after login

package.json의 종속성을 업데이트하기 위해 npm을 얻기 위해 --save 플래그를 사용해야 했던 옛날을 기억하시는 분들도 계실 것입니다. 다행히 더 이상 그럴 필요가 없습니다.

피어 종속성 추가

피어 종속성은 프로젝트가 특정 버전의 npm 패키지와 호환됨을 지정하는 데 사용됩니다. 좋은 예가 Angular와 React입니다.

피어 종속성을 추가하려면 실제로 package.json 파일을 수동으로 수정해야 합니다. 예를 들어, 구성 요소 라이브러리 프로젝트의 경우 사용 중인 프레임워크에 따라 angular/core 또는 react를 피어 종속성으로 추가하는 것이 좋습니다.

따라서 패키지가 React 18용으로 빌드되도록 지정하려면 다음과 같은 내용을 포함할 수 있습니다.

"peerDependencies": {
   "react": "^18.0.0",
}
Copy after login

또는 Angular 버전 17과 18 모두에서 구성 요소 라이브러리를 테스트했지만 아직 출시되지 않았기 때문에 19에서는 테스트하지 않았다고 말하고 싶을 수도 있습니다. 그런 다음 다음을 사용할 수 있습니다.

"peerDependencies": {
   "@angular/core": ">=17.0.0 || <19"
}
Copy after login

About Conflicts

I get a lot of questions about whether a certain npm package should go into dependencies or into peerDependencies. The key to making this decision involves understanding how npm deals with version conflicts.

If you have read my previous articles, you know I like you to be able to do this stuff along with me! So feel free to work along with me for this little npm experiment.

conflict-test Project

To get started let’s create a trivial test project. I am going to name mine:
conflict-test

I created it like this:

md conflict-test
cd conflict-test
npm init -y
Copy after login

I then manually edited the package.json file and added two dependencies:

"dependencies": {
    "todd-a": "^1.0.0",
    "todd-b": "^1.0.0"
}
Copy after login

These todd-a and todd-b packages also have their own dependencies:

todd-a

"dependencies": {
    "lodash": "^4.17.11",
    "todd-child": "^1.0.0"
}
Copy after login

todd-b

"dependencies": {
    "lodash": "^4.17.11",
    "todd-child": "^2.0.0"
}
Copy after login

The thing I want you to notice here is that todd-a and todd-b use the same version of lodash. But, they have a version conflict for todd-child:
todd-a uses todd-child version 1.0.0
todd-b uses todd-child version 2.0.0

Now I know that, like me, you are keenly interested in seeing how npm handles this version conflict. In my main project conflict-test I run npm install. As we would expect, npm magically installs the todd-a and todd-b packages in our node_modules folder. It also adds the packages that they depend on (the transitive dependencies). So after running npm install we take a look at the node_modules folder. It looks like this:

node_modules
├── lodash 4.17.11
├── todd-a 1.0.0
├── todd-b 1.0.0
│   └── node_modules
│       └── todd-child 2.0.0
└── todd-child 1.0.0
Copy after login

The interesting thing about this is that our project has one copy of lodash. But, it has two copies of todd-child! Notice that todd-b gets its own private copy of todd-child 2.0.0.

So here is the rule:

npm deals with version conflicts by adding duplicate private versions of the conflicted package.

An Approach to Peer Dependencies

As we saw from our experiment with npm version conflicts, if you add a package to your dependencies, there is a chance it may end up being duplicated in node_modules.

Sometimes, having two versions of the same package is fine. However, some packages will cause conflicts when there are two different versions of them in the same code base.

For example, assume our component library was created using React v15. We wouldn’t want our package adding another completely different version of react when someone adds it as a dependency to their React v18 application.

The key is:
We don’t want our library adding another version of a package to node-modules when that package could conflict with an existing version and cause problems.

peerDependencies or dependencies?

So this brings us to the main question for our dependencies:

When my package depends on another package, should I put it in dependencies or peerDependencies?

Well, as with most technical questions: It depends.

Peer Dependencies express compatibility. For example, you will want to be specific about which version of Angular or React your library is compatible with.

The Guidelines

Favor using Peer Dependencies when one of the following is true:

  • Having multiple copies of a package would cause conflicts
  • The dependency is visible in your interface
  • You want the developer to decide which version to install

Let’s take the example of angular/core. Obviously, if you are creating an Angular Library, angular/core is going to be a very visible part of your library’s interface. Hence, it belongs in your peerDependencies.

However, maybe your library uses Moment.js internally to process some time related inputs. Moment.js most likely won’t be exposed in the interface of your Angular or React components. Hence, it belongs in your dependencies.

Angular or React as a Dependency

Given that you are going to specify in your documentation that your library is a set of Angular or React Components, you may be asking the question:

Do I even need to specify angular/core as a dependency? If someone is using my library, they will already have an existing Angular project.

Good question!

Yes, we can usually assume that for our Angular or React specific library the Workspace will already have the Angular or React packages available. Hence, technically we wouldn’t need to bother adding them to our list of dependencies.

Wir möchten dem Entwickler jedoch unbedingt mitteilen, mit welchen Angular- oder React-Versionen unsere Bibliothek kompatibel ist. Daher empfehle ich folgende Vorgehensweise:

Fügen Sie mindestens das Angular/Core- oder React-Paket für die kompatible Version zu Ihren PeerDependencies hinzu.

Auf diese Weise wird Entwicklern eine Warnung angezeigt, wenn sie versuchen, Ihre React 18-Komponentenbibliothek in ihrem React 16-Projekt zu verwenden. Machen Sie sich nicht die Mühe, die anderen Angular- oder React-Pakete hinzuzufügen. Sie können davon ausgehen, dass sie, wenn sie über Angular/Core oder React verfügen, über die anderen zugehörigen Bibliotheken verfügen.

Abschließend

Im Zweifelsfall sollten Sie sich wahrscheinlich für die Verwendung von peerDependencies entscheiden. Dadurch können die Benutzer Ihres Pakets selbst entscheiden, welche Pakete sie hinzufügen möchten.

The above is the detailed content of npm Peer Dependencies for the Professional Developer. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!