The main function of NPM is to install and manage the dependencies of our project. To do this, as we know, it registers the dependencies in the package.json
file.
These dependencies are organized into two categories:
Dependencies
: Dependencies required for executionDevDependencies
: Dependencies needed only during development
If we have our dependencies correctly configured in the package.json
file, we can install them simply with the following command,
npm install
This command will read the package.json
file and download all the dependencies specified in the dependencies
section. These dependencies will be stored in a folder called node_modules
in the project directory.
This is very common when we download an Open Source project. When publishing a project, it is stored in repositories (like Github) without the libraries. This makes sense, it is to save space.
It is a very common mistake, at first, to download an Open Source project and think that it doesn’t work. Often, it is simply that we have forgotten to install the dependencies with this command
Examples
Installation of required dependencies
When npm install
is run without any additional options, NPM will install the dependencies found under the dependencies
section in the package.json
file. These are the dependencies necessary for the application to function correctly in a production environment.
Suppose we have a package.json
file like the following,
{
"name": "my-project",
"version": "1.0.0",
"dependencies": {
"express": "^4.17.1",
"lodash": "^4.17.21"
}
}
In this case, npm install
will download and install the latest versions of the express
and lodash
libraries.
Installation of development dependencies
If we want to install the dependencies necessary for the development of the project (such as unit tests, build tools, or code style tests), we must use the --dev
option or its shorthand -D
. For example:
npm install --dev
This will install all the dependencies found in the devDependencies
section of our package.json
file.
Remember that these dependencies will not be included in the final package when we distribute our application