Introduction to npm
npm is the standard package manager for Node.js.
In September 2022 over 2.1 million packages were reported being listed in the npm registry, making it the biggest single language code repository on Earth, and you can be sure there is a package for (almost!) everything.
It started as a way to download and manage dependencies of Node.js packages, but it has since become a tool used also in frontend JavaScript.
Packages
npm installs, updates and manages downloads of dependencies of your project. Dependencies are pre-built pieces of code, such as libraries and packages, that your Node.js application needs to work.
Installing all dependencies
If a project has apackage.json file, by running
node_modules folder, creating it if it’s not existing already.
Installing a single package
You can also install a specific package by running<package-name> to the package.json file dependencies. Before version 5, you needed to add the flag --save.
Often you’ll see more flags added to this command:
--save-devinstalls and adds the entry to thepackage.jsonfile devDependencies--no-saveinstalls but does not add the entry to thepackage.jsonfile dependencies--save-optionalinstalls and adds the entry to thepackage.jsonfile optionalDependencies--no-optionalwill prevent optional dependencies from being installed
-S:--save-D:--save-dev-O:--save-optional
Updating packages
Updating is also made easy, by runningnpm will check all packages for a newer version that satisfies your versioning constraints.
You can specify a single package to update as well:
Versioning
In addition to plain downloads,npm also manages versioning, so you can specify any specific version of a package, or require a version higher or lower than what you need.
Many times you’ll find that a library is only compatible with a major release of another library.
Or a bug in the latest release of a lib, still unfixed, is causing an issue.
Specifying an explicit version of a library also helps to keep everyone on the same exact version of a package, so that the whole team runs the same version until the package.json file is updated.
In all those cases, versioning helps a lot, and npm follows the semantic versioning (semver) standard.
You can install a specific version of a package, by running
Running tasks
Thepackage.json file supports a format for specifying command line tasks that can be run by using