Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Monday, November 7, 2022

NPM and Dependencies


 


Npm is a software registry, which holds hundreds of thousands libraries. It is used in a JavaScript based project to install dependencies.

The dependencies are added using npm, which install the dependencies in a transitive manner. This means that in case we install library A, which requires library B, and library B requires library C, then A, B, and C are all installed.

Not only that but npm also manages the versions requirements, so if A requires a specific version of B. Unlike other tools (like maven) npm can install different versions o the same library. See a nice example in the post: Understanding npm dependency resolution.


Still, there are some keynotes of npm usage for an npm user to keep in mind.


First, always install dependencies using install flag, e.g.:

npm install my-dependency-library

This does the following:

  1. Adds the recent version of the library to the package.json file.
  2. Add all the transitive dependencies of the library to the package-lock.json file.
  3. Install (downloads) all the transitive dependencies to the node_modules folder.

Second, npm does not start in vein every run. It inspects the current content of the package.json, package-lock.json, and the node_modules folder, and prefer using the dependencies from there instead of downloading new ones. This means, that if something went wrong, and we want to start a fresh dependencies installation, we need to delete both package-lock.json and the node_modules folder before running npm install.

Third, a very common error is "npm unable to resolve dependency tree". This is due to a dependency resolving algorithm change in recent npm versions, as explained here. To solve this, start a fresh dependencies installation (as specified above), and run npm with the --legacy-peer-deps flag.



No comments:

Post a Comment