Newcomers to Node and NPM often ask how to install a specific version of a certain NPM package. There are several ways to accomplish this. First, let’s start with the basic NPM CLI syntax:
npm install lodash
This command installs lodash
in the current folder and fetches the latest available version.
If you know the exact version of the package, you can append it to the package name after the @ character:
npm install lodash@4.17.4
You can look up the latest version for any NPM package at npmjs.com.
If you don’t know the exact version of the package, NPM allows using semantic ranges to define the version. For example,
npm install lodash@^4.0.0
This command will install the latest 4.x.x version. You can learn more about the syntax of semantic versioning at docs.npmjs.com.
Both aforementioned examples don’t modify package.json and don’t add installed modules to the list of dependencies. Use --save
to add the installed module to the package.json’s dependencies and --save-dev
to add it to devDependencies. If you install a module without defining a specific version (i.e. without any version or using a semantic range), NPM will add the semantic range to the package.json as is. To prevent this, use --save-exact
flag in addition to --save
or --save-dev
. This flag will force NPM to store the exact module version in the package.json.
Examples
npm install lodash --save --save-exact
- installs the latest version and saves the exact version in thedependencies
in the package.json.npm install lodash --save-dev --save-exact
- installs the latest version and saves the exact version in thedevDependencies
map in the package.json.npm install lodash --save
- installs the latest version and saves the semantic range in thedependencies
in the package.json. E.g."lodash": "^4.17.4"
.
Caveats
- Specifying
--save-exact
alone is not sufficient. You need to define either--save
or--save-dev
and--save-exact
. For example,npm install mocha --save-dev --save-exact
ornpm install lodash --save --save-exact
--save
,--save-exact
,--save-dev
obviously don’t work together with the-g
flag which installs the module globally.
Learning Node.js? Get the book Node.js Design Patterns - Second Edition: Master best practices to build modular and scalable server-side web applications