Maison > interface Web > js tutoriel > le corps du texte

Dépendances entre pairs npm pour le développeur professionnel

Mary-Kate Olsen
Libérer: 2024-10-14 13:27:29
original
721 Les gens l'ont consulté

npm Peer Dependencies for the Professional Developer

Dalam artikel ini, saya menjelaskan apa itu npm Peer Dependencies dan terutamanya bila anda patut menggunakannya. Peer Dependencies disenaraikan dalam fail package.json projek anda dalam objek peerDependencies.

Untuk memanfaatkan artikel ini sepenuhnya, anda harus mempunyai sekurang-kurangnya pemahaman pengenalan npm.

Kandungan

Dalam artikel ini:

  1. Kami akan membandingkan dengan tepat cara Ketergantungan Rakan Sebaya berfungsi berbanding Ketergantungan biasa.
  2. Kami akan melihat beberapa contoh kedua-dua Ketergantungan Rakan Sebaya dan Ketergantungan.
  3. Kemudian, kita akan meneliti cara npm mengendalikan konflik versi.
  4. Akhir sekali, mempunyai asas yang kukuh dalam genggaman kami, kami akan meletakkan pendekatan untuk memutuskan bila Kebergantungan Rakan Sebaya sesuai.

Senario

Untuk memastikan ia nyata, anggap anda sedang mencipta Pustaka Komponen Sudut atau React atau malah hanya fail JavaScript ringkas yang mengeksport beberapa fungsi.

Projek anda bergantung pada pakej daripada Pendaftaran npm. Pakej ini ialah pergantungan projek anda.

Anda mahu mencipta pakej npm anda sendiri daripada projek anda. Jadi anda menggunakan pek npm untuk menjana pakej npm daripada projek anda. Anda mungkin memutuskan untuk menerbitkannya ke Pejabat Pendaftaran npm.

Pasukan lain kemudiannya boleh mencari pustaka komponen anda sebagai pakej pada Pendaftaran npm. Mereka boleh menggunakan pemasangan npm untuk menambah pakej anda sebagai pergantungan dalam projek mereka sendiri. Kami menggunakan Dependencies dan Peer Dependencies dalam package.json untuk memberitahu projek-projek lain ini pakej yang perlu ditambah untuk pustaka komponen kami berfungsi.

Ketergantungan Berbanding Ketergantungan Rakan Sebaya

Pada tahap paling asas mereka di sini ialah bagaimana Pergantungan dan Pergantungan Rakan Sebaya berfungsi:

Kebergantungan

Kebergantungan disenaraikan dalam fail package.json projek anda dalam objek kebergantungan.

Apabila anda menambah pakej dalam kebergantungan kod anda, anda berkata:

  • Kod saya memerlukan pakej ini untuk dijalankan.
  • Jika pakej ini belum wujud dalam direktori node_modules saya, kemudian tambahkannya secara automatik.
  • Selain itu, tambahkan sebarang pakej yang disenaraikan dalam kebergantungan pakej ini. Pakej ini dipanggil Ketergantungan Transitif.

Kebergantungan Rakan Sebaya

Peer Dependencies disenaraikan dalam fail package.json projek anda dalam objek peerDependencies.

Dengan menambahkan pakej dalam peerDependencies kod anda, anda berkata:

  • Kod saya serasi dengan versi pakej ini.
  • Jika pakej ini sudah wujud dalam node_modules, jangan lakukan apa-apa.
  • Jika pakej ini belum wujud dalam direktori node_modules atau ia adalah versi yang salah, jangan tambahkannya. Tetapi, tunjukkan amaran kepada pengguna bahawa ia tidak ditemui.

Menambah Ketergantungan

Jadi, kami menambah kebergantungan dalam fail package.json folder pakej npm kami. Mari lihat dengan tepat cara kami menambah pakej sebagai kebergantungan dan beberapa contoh kebergantungan pakej.

Menambah Kebergantungan

A Pergantungan ialah pakej npm yang bergantung pada kod kami agar dapat dijalankan. Beberapa pakej popular yang boleh ditambah sebagai kebergantungan ialah lodash, D3 dan chartjs.

Kami menambah pergantungan biasa seperti ini:

npm install lodash
Copier après la connexion

npm menambah nama pakej dan versi pada objek dependencies dalam fail package.json projek kami.

"dependencies": {
  "lodash": "^4.17.11"
}
Copier après la connexion

Sesetengah daripada anda mungkin mengingati zaman dahulu apabila kami terpaksa menggunakan bendera --save untuk mendapatkan npm mengemas kini kebergantungan dalam package.json. Syukurlah, kita tidak perlu berbuat demikian lagi.

Menambah Kebergantungan Rakan Sebaya

Ketergantungan Rakan Sebaya digunakan untuk menentukan bahawa projek kami serasi dengan versi khusus pakej npm. Contoh yang baik ialah Angular dan React.

Untuk menambah Ketergantungan Rakan Sebaya anda sebenarnya perlu mengubah suai fail package.json anda secara manual. Contohnya, untuk projek perpustakaan komponen, bergantung pada rangka kerja yang anda gunakan, saya syorkan menambah sudut/teras atau bertindak balas sebagai pergantungan rakan sebaya.

Jadi, jika anda ingin menentukan bahawa pakej anda dibina untuk React 18, anda boleh memasukkan sesuatu seperti ini:

"peerDependencies": {
   "react": "^18.0.0",
}
Copier après la connexion

Atau mungkin anda ingin mengatakan bahawa anda telah menguji pustaka komponen anda dengan kedua-dua versi Angular 17 dan 18 tetapi bukan 19 kerana ia belum keluar lagi. Kemudian anda boleh menggunakan:

"peerDependencies": {
   "@angular/core": ">=17.0.0 || <19"
}
Copier après la connexion

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
Copier après la connexion

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

"dependencies": {
    "todd-a": "^1.0.0",
    "todd-b": "^1.0.0"
}
Copier après la connexion

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

todd-a

"dependencies": {
    "lodash": "^4.17.11",
    "todd-child": "^1.0.0"
}
Copier après la connexion

todd-b

"dependencies": {
    "lodash": "^4.17.11",
    "todd-child": "^2.0.0"
}
Copier après la connexion

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
Copier après la connexion

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.

Cependant, nous souhaitons vraiment indiquer au développeur avec quelles versions Angular ou React notre bibliothèque est compatible. Je recommande donc l'approche suivante :

Ajoutez au moins le package angulaire/core ou React pour la version compatible à vos peerDependencies.

De cette façon, les développeurs verront un avertissement s'ils tentent d'utiliser votre bibliothèque de composants React 18 dans leur projet React 16. Ne vous embêtez pas à ajouter les autres packages Angular ou React. Vous pouvez supposer que s'ils ont angulaire/core ou réagissent, ils ont les autres bibliothèques associées.

En conclusion

En cas de doute, vous devriez probablement vous tourner vers l'utilisation de peerDependencies. Cela permet aux utilisateurs de votre package de faire leur propre choix quant aux packages à ajouter.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!