Home Web Front-end JS Tutorial npm Peer Dependencies for the Professional Developer

npm Peer Dependencies for the Professional Developer

Oct 14, 2024 pm 01:27 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles