How to update each dependency in package.json to the latest version? - node.js

I copied package.json from another project and now want to bump all of the dependencies to their latest versions since this is a fresh project and I don't mind fixing something if it breaks.
What's the easiest way to do this?
The best way I know is to run npm info express version then update each dependency in package.json manually. There must be a better way.
{
"name": "myproject",
"description": "my node project",
"version": "1.0.0",
"dependencies": {
"express": "^3.0.3", // how do I get these bumped to latest?
"mongodb": "^1.2.5",
"underscore": "^1.4.2"
}
}
For Yarn specific solutions refer to this Stack Overflow thread.

Looks like npm-check-updates is the only way to make this happen now.
npm i -g npm-check-updates
ncu -u
npm install
On npm <3.11:
Simply change every dependency's version to *, then run npm update --save. (Note: broken in recent (3.11) versions of npm).
Before:
"dependencies": {
"express": "*",
"mongodb": "*",
"underscore": "*",
"rjs": "*",
"jade": "*",
"async": "*"
}
After:
"dependencies": {
"express": "~3.2.0",
"mongodb": "~1.2.14",
"underscore": "~1.4.4",
"rjs": "~2.10.0",
"jade": "~0.29.0",
"async": "~0.2.7"
}
Of course, this is the blunt hammer of updating dependencies. It's fine if—as you said—the project is empty and nothing can break.
On the other hand, if you're working in a more mature project, you probably want to verify that there are no breaking changes in your dependencies before upgrading.
To see which modules are outdated, just run npm outdated. It will list any installed dependencies that have newer versions available.
For Yarn specific solution, refer to this StackOverflow answer.

npm-check-updates is a utility that automatically adjusts a package.json with the
latest version of all dependencies
see https://www.npmjs.org/package/npm-check-updates
$ npm install -g npm-check-updates
$ ncu -u
$ npm install
[EDIT] A slightly less intrusive (avoids a global install) way of doing this if you have a modern version of npm is:
$ npx npm-check-updates -u
$ npm install

Updated for npm v2+
npm 2+ (Node 0.12+):
npm outdated
npm update
git commit package-lock.json
Ancient npm (circa 2014):
npm install -g npm-check-updates
npm-check-updates
npm shrinkwrap
git commit package-lock.json
Be sure to shrinkwrap your deps, or you may wind up with a dead project. I pulled out a project the other day and it wouldn't run because my deps were all out of date/updated/a mess. If I'd shrinkwrapped, npm would have installed exactly what I needed.
Details
For the curious who make it this far, here is what I recommend:
Use npm-check-updates or npm outdated to suggest the latest versions.
# `outdated` is part of newer npm versions (2+)
$ npm outdated
# If you agree, update.
$ npm update
# OR
# Install and use the `npm-check-updates` package.
$ npm install -g npm-check-updates
# Then check your project
$ npm-check-updates
# If you agree, update package.json.
$ npm-check-updates -u
###Then do a clean install (w/o the rm I got some dependency warnings)
$ rm -rf node_modules
$ npm install
Lastly, save exact versions to npm-shrinkwrap.json with npm shrinkwrap
$ rm npm-shrinkwrap.json
$ npm shrinkwrap
Now, npm install will now use exact versions in npm-shrinkwrap.json
If you check npm-shrinkwrap.json into git, all installs will use the exact same versions.
This is a way to transition out of development (all updates, all the time) to production (nobody touch nothing).
npm outdated
npm-check-updates
npm shrinkwrap
p.s. Yarn is sending your package list to Facebook.

To update one dependency to its lastest version without having to manually open the package.json and change it, you can run
npm install {package-name}#* {save flags?}
i.e.
npm install express#* --save
This flow is compatible with workspaces, i.e.
npm --workspace some/package install express#*
For reference, npm-install
Note: Some npm versions may need latest flag instead, i.e. npm install express#latest
As noted by user Vespakoen on a rejected edit, it's also possible to update multiple packages at once this way:
npm install --save package-nave#* other-package#* whatever-thing#*
He also apports a one-liner for the shell based on npm outdated. See the edit for code and explanation.
PS: I also hate having to manually edit package.json for things like that ;)

If you happen to be using Visual Studio Code as your IDE, this is a fun little extension to make updating package.json a one click process.
note: After updating packages in package.json file, run npm update to install the new versions.
Version Lens
GitLab Repo

This works as of npm 1.3.15.
"dependencies": {
"foo": "latest"
}

Use * as the version for the latest releases, including unstable
Use latest as version definition for the latest stable version
Modify the package.json with exactly the latest stable version number using LatestStablePackages
Here is an example:
"dependencies": {
"express": "latest" // using the latest STABLE version
, "node-gyp": "latest"
, "jade": "latest"
, "mongoose": "*" // using the newest version, may involve the unstable releases
, "cookie-parser": "latest"
, "express-session": "latest"
, "body-parser": "latest"
, "nodemailer":"latest"
, "validator": "latest"
, "bcrypt": "latest"
, "formidable": "latest"
, "path": "latest"
, "fs-extra": "latest"
, "moment": "latest"
, "express-device": "latest"
},

To see which packages have newer versions available, then use the following command:
npm outdated
to update just one dependency just use the following command:
npm install yourPackage#latest
For example:
My package.json file has dependency:
"#progress/kendo-angular-dateinputs": "^1.3.1",
then I should write:
npm install #progress/kendo-angular-dateinputs#latest
What does --save-dev mean?
npm install #progress/kendo-angular-dateinputs#latest --save-dev
As npm install docs says:
-D, --save-dev: Package will appear in your devDependencies.

I really like how npm-upgrade works. It is a simple command line utility that goes through all of your dependencies and lets you see the current version compared to the latest version and update if you want.
Here is a screenshot of what happens after running npm-upgrade in the root of your project (next to the package.json file):
For each dependency you can choose to upgrade, ignore, view the changelog, or finish the process. It has worked great for me so far.
To be clear this is a third party package that needs to be installed before the command will work. It does not come with npm itself:
npm install -g npm-upgrade
Then from the root of a project that has a package.json file:
npm-upgrade

The only caveat I have found with the best answer above is that it updates the modules to the latest version. This means it could update to an unstable alpha build.
I would use that npm-check-updates utility.
My group used this tool and it worked effectively by installing the stable updates.
As Etienne stated above: install and run with this:
$ npm install -g npm-check-updates
$ npm-check-updates -u
$ npm install

I use npm-check to achieve this.
npm i -g npm npm-check
npm-check -ug #to update globals
npm-check -u #to update locals
Another useful command list which will keep exact version numbers in package.json
npm cache clean
rm -rf node_modules/
npm i -g npm npm-check-updates
ncu -g #update globals
ncu -u #update locals
npm I
Update: You can use yarn upgrade-interactive --latest if you are using yarn

Here is a basic regex to match semantic version numbers so you can quickly replace them all with an asterisk.
Semantic Version Regex
([>|<|=|~|^|\s])*?(\d+\.)?(\d+\.)?(\*|\d+)
How to use
Select the package versions you want to replace in the JSON file.
Input the regex above and verify it's matching the correct text.
Replace all matches with an asterisk.
Run npm update --save

If you want to use a gentle approach via a beautiful (for terminal) interactive reporting interface I would suggest using npm-check.
It's less of a hammer and gives you more consequential knowledge of, and control over, your dependency updates.
To give you a taste of what awaits here's a screenshot (scraped from the git page for npm-check):

This feature has been introduced in npm v5. update to npm using npm install -g npm#latest and
to update package.json
delete /node_modules and package-lock.json (if you have any)
run npm update. this will update the dependencies package.json to the latest, based on semver.
to update to very latest version. you can go with npm-check-updates

As of npm version 5.2.0, there is a way to run this in a single line without installing any additional packages to your global npm registry nor locally to your application. This can be done by leveraging the new npx utility that's bundled with npm. (Click here to learn more.)
Run the following command in the root of your project:
npx npm-check-updates -u && npm i

I recently had to update several projects that were using npm and package.json for their gruntfile.js magic. The following bash command (multiline command) worked well for me:
npm outdated --json --depth=0 | \
jq --ascii-output --monochrome-output '. | keys | .[]' | \
xargs npm install $1 --save-dev
The idea here:
To pipe the npm outdated output as json, to jq
(jq is a json command line parser/query tool)
(notice the use of --depth argument for npm outdated)
jq will strip the output down to just the top level package name only.
finally xargs puts each LIBRARYNAME one at a time into a npm install LIBRARYNAME --save-dev command
The above is what worked for me on a machine runnning:
node=v0.11.10 osx=10.9.2 npm=1.3.24
this required:
xargs http://en.wikipedia.org/wiki/Xargs (native to my machine I believe)
and
jq http://stedolan.github.io/jq/ (I installed it with brew install jq)
Note: I only save the updated libraries to package.json inside of the json key devDependancies by using --save-dev, that was a requirement of my projects, quite possible not yours.
Afterward I check that everything is gravy with a simple
npm outdated --depth=0
Also, you can check the current toplevel installed library versions with
npm list --depth=0

If you use yarn, the following command updates all packages to their latest version:
yarn upgrade --latest
From their docs:
The upgrade --latest command upgrades packages the same as the upgrade command, but ignores the version range specified in package.json. Instead, the version specified by the latest tag will be used (potentially upgrading the packages across major versions).

Updtr!
Based on npm outdated, updtr installs the latest version and runs npm test for each dependency. If the test succeeds, updtr saves the new version number to your package.json. If the test fails, however, updtr rolls back its changes.
https://github.com/peerigon/updtr

Safe update
Use 'npm outdated' to discover dependencies that are out of date.
Use 'npm update' to perform safe dependency upgrades.
Use 'npm install #latest' to upgrade to the latest major version of a package.
Breaking Update
Use 'npx npm-check-updates -u'.
'npm install' to upgrade all dependencies to their latest major versions.

If you are using yarn, yarn upgrade-interactive is a really sleek tool that can allow you to view your outdated dependencies and then select which ones you want to update.
More reasons to use Yarn over npm. Heh.

Commands that I had to use to update package.json for NPM 3.10.10:
npm install -g npm-check-updates
ncu -a
npm install
Background:
I was using the latest command from #josh3736 but my package.json was not updated. I then noticed the description text when running npm-check-updates -u:
The following dependency is satisfied by its declared version range,
but the installed version is behind. You can install the latest
version without modifying your package file by using npm update. If
you want to update the dependency in your package file anyway, run ncu
-a.
Reading the documentation for npm-check-updates you can see the difference:
https://www.npmjs.com/package/npm-check-updates
-u, --upgrade: overwrite package file
-a, --upgradeAll: include even those dependencies whose latest version satisfies the declared semver dependency
ncu is an alias for npm-check-updates as seen in the message when typing npm-check-updates -u:
[INFO]: You can also use ncu as an alias

If you don't want to install global npm-check-updates you can simply run that:
node -e "const pk = JSON.parse(require('fs').readFileSync('package.json', 'utf-8'));require('child_process').spawn('npm', ['install', ...Object.keys(Object.assign({},pk.dependencies, pk.devDependencies)).map(a=>a+'#latest')]).stdout.on('data', d=>console.log(d.toString()))"

If you're looking for an easier solution that doesn't involve installing npm packages, I'd checkout updatepackagejson.com

The above commands are unsafe because you might break your module when switching versions.
Instead I recommend the following
Set actual current node modules version into package.json using npm shrinkwrap command.
Update each dependency to the latest version IF IT DOES NOT BREAK YOUR TESTS using https://github.com/bahmutov/next-update command line tool
npm install -g next-update
// from your package
next-update

Try following command if you using npm 5 and node 8
npm update --save

I solved this by seeing the instructions from https://github.com/tjunnone/npm-check-updates
$ npm install -g npm-check-updates
$ ncu
$ ncu -u # to update all the dependencies to latest
$ ncu -u "specific module name" #in case you want to update specific dependencies to latest

I found another solution for recent version of NPM. What I want to do is to replace all the "*" dependencies with the explicit lastest version number. None of the methods discussed has worked for me.
What I did:
Replace all "*" with "^0.0.0"
Run npm-check-updates -u
Everything in package.json now is updated to the last version.

As it's almost 10 years since the original question, many of the answers are either outdated or not recommended.
I would use something which is package manager agnostic i.e. can work with npm, pnpm, yarn or others.
Lately I have been using taze
You can either add it to your dev dependencies and run from there or run without installation with npx taze or pnpx taze, etc.

The following code (which was accepted) wrote me something like "it takes too long blah-blah" and did nothing. Probably using the global flag was the problem, idk.
npm i -g npm-check-updates
ncu -u
npm install
I decided to use my text editor and follow a semi-manual approach instead.
I copied a list like this (just a lot longer) from the dev dependencies of my package.json to the notepad++ text editor:
"browserify": "10.2.6",
"expect.js": "^0.3.1",
"karma": "^0.13.22",
"karma-browserify": "^5.2.0",
I set the search mode to regular expression, used the ^\s*"([^"]+)".*$ pattern to get the package name and replaced it with npm uninstall \1 --save-dev \nnpm install \1 --save-dev. Clicked on "replace all". The otput was this:
npm uninstall browserify --save-dev
npm install browserify --save-dev
npm uninstall expect.js --save-dev
npm install expect.js --save-dev
npm uninstall karma --save-dev
npm install karma --save-dev
npm uninstall karma-browserify --save-dev
npm install karma-browserify --save-dev
I copied it back to bash and hit enter. Everything was upgraded and working fine. That's all.
"browserify": "^16.1.0",
"expect.js": "^0.3.1",
"karma": "^2.0.0",
"karma-browserify": "^5.2.0",
I don't think it is a big deal, since you have to do it only every now and then, but you can easily write a script, which parses the package.json and upgrades your packages. I think it is better this way, because you can edit your list if you need something special, for example keeping the current version of a lib.

It's wild to me that 90% of answers is some variant of "use npm-check-updates". Here's what I do (relevant code):
{
"devDependencies": {
"updates": "^13.0.5" // the version here could be "latest" or "*" tbh...
},
"scripts": {
"test:dependencies": "updates --update ./",
}
}
Running npm run test:dependencies (or whatever your dependency update script is called) will check your package.json for the latest versions of every package listed, and it'll let you know when the latest version was published. Run npm i after that and you'll be up to date!
Also, unlike npm-check-updates, updates has zero dependencies (ncu has 29, at the time of this post).

Related

Is there any way to fix package-lock.json lockfileVersion so npm uses a specific format?

If two different developers are using different versions of node (12/15) & npm (6/7) in a project that was originally created using a package-lock.json "lockfileVersion": 1, when the developer using npm 7x installs new packages it seems that the package-lock.json is re-created using "lockfileVersion": 2.
This seems to cause issues for the developer using npm v6, as it tries to work with the lockfileVersion 2, but it ends up producing new diffs.
npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion#1, but package-lock.json was generated for lockfileVersion#2. I'll try to do my best with it!
Is there any way to specify to newer versions of npm to only use "lockfileVersion": 1? Or do we just have to get all devs on the same version of npm?
Is there any way to specify to newer versions of npm to only use "lockfileVersion": 1? Or do we just have to get all devs on the same version of npm?
I will advise you to pin the Node/NPM version and align it across your environments (development, staging, and production).
you can leverage nvm for managing Node version by adding to your project .nvmrc file (don't forget to store it in your source control).
for instance, .nvmrc will look like:
$ cat .nvmrc
14.15.0
then, you can use nvm install && nvm use to use the pinned version of Node.
NPM also supports engines:
You can specify the version of node that your stuff works on:
{ "engines" : { "node" : ">=0.10.3 <0.12" } }
And, like with dependencies, if you don't specify the version (or if you specify "*" as the version), then any version of Node will do.
If you specify an "engines" field, then npm will require that "node" be somewhere on that list. If "engines" is omitted, then npm will just assume that it works on Node.
You can also use the "engines" field to specify which versions of npm are capable of properly installing your program. For example:
{ "engines" : { "npm" : "~1.0.20" } }
Unless the user has set the engine-strict config flag, this field is advisory only and will only produce warnings when your package is installed as a dependency.
When utilizing the engines field and make npm fail when the version constraints are unmet, set engine-strict=true (since it is false by default) in .npmrc file or as an npm_config_engine_strict=true environment variable
If set to true, then npm will stubbornly refuse to install (or even consider installing) any package that claims to not be compatible with the current Node.js version.
This can be overridden by setting the --force flag.
Another approach is to use a Docker container as a runtime environment for development and execution, which implies that you neither need to install Node, nor NPM. e.g.
$ mkdir my-project
$ cd my-project
$ docker run --rm -it -v $PWD:/app --entrypoint /bin/bash --workdir /app node:14.15.0
root#4da6ee3c2ac0:/app# npm init -y
Wrote to /app/package.json:
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
root#4da6ee3c2ac0:/app# npm install
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN app#1.0.0 No description
npm WARN app#1.0.0 No repository field.
up to date in 1.694s
found 0 vulnerabilities
root#4da6ee3c2ac0:/app# exit
exit
$ ls -x1
package-lock.json
package.json
As you can see, with neither Node, nor NPM:
Created a new directory for a fresh project
Spun up a Node Docker container, which comes with Node and NPM
Created a new project (npm init -y)
Exited the Docker container
Listed the files within the working directory, where the container was spun
Since the docker run command above is long, you might wish to leverage docker-compose for a more streamlined workflow.
npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion#1, but package-lock.json was generated for lockfileVersion#2. I'll try to do my best with it!
to overcome this issue, running the command
npm i -g npm#latest
globally and running the command
npm i npm#latest
in the project file helped me resolve the issue.
As far as I can see the npm docs say that npm v6 will work with version 2 lockfiles in spite of the warning, so you don't need to do any of the things suggested in the accepted answer and can safely ignore the warning message.
In the npm 7 release notes they said:
One change to take note of is the new lockfile format, which is
backwards compatible with npm 6 users. The lockfile v2 unlocks the
ability to do deterministic and reproducible builds to produce a
package tree.
In the npm docs it says (my emphasis):
lockfileVersion
An integer version, starting at 1 with the version number of this
document whose semantics were used when generating this
package-lock.json.
Note that the file format changed significantly in npm v7 to track
information that would have otherwise required looking in node_modules
or the npm registry. Lockfiles generated by npm v7 will contain
lockfileVersion: 2.
No version provided: an "ancient" shrinkwrap file from a version of npm prior to npm v5.
1: The lockfile version used by npm v5 and v6.
2: The lockfile version used by npm v7, which is backwards compatible to v1 lockfiles.
3: The lockfile version used by npm v7, without backwards compatibility affordances. This is used for the hidden lockfile at
node_modules/.package-lock.json, and will likely be used in a future
version of npm, once support for npm v6 is no longer relevant.
This is why they can automatically upgrade lockfiles from v1 to v2, which you mention, without breaking anything.
As of version 8.1.0 there is a flag --lockfile-version in npm with which you can override the default lock file version:
npm i --lockfile-version 3
Here is the link to the original PR.
I encountered the same problem today. I am working on a project with a developer having a different version of npm (>7) and i ran into the same issue. I simply upgraded my npm version to the latest version which was being used by the other developer as mentioned above.
Following are the steps to upgrade your npm (for windows):
First, ensure that you can execute scripts on your system by running the following command from an elevated PowerShell. To run PowerShell as Administrator, click Start, search for PowerShell, right-click PowerShell and select Run as Administrator.
Next execute following commands:
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
Then, to install and use this upgrader tool, run the following command (also from an elevated PowerShell or cmd.exe). Note: This tool requires at least Node v8
npm install --global --production npm-windows-upgrade
npm-windows-upgrade
Want to just install the latest version? Sure:
npm-windows-upgrade --npm-version latest
Now you can select the version which you want to install from the command line.
https://github.com/felixrieseberg/npm-windows-upgrade
The above link is the tool which I've used. This tool is both for Linux/Windows. I hope it will help.
There is a much more simpler solution than using nvm:
npx npm#6.14.17 i --save
With this you can generate a new lockfile with version 1, use the latest node js version and you don't need to change anything on your machine.
lockfile construction depends on the npm version. v7+ will create lockfile 2, below will create lockfile v1.
Lockfile v2 is backwards compatible so people running npm < v6 will be ok to use it, but i am looking at a circleci build failure on my second screen which suggests some of the npm packages we use are not compatible with lockfile v2... i.e. old npm packages may not be as well maintained and compatible with lockfile v2.
Hence probably the best course of action is to dockerise and isolate your env.
This is why docker was invented! Get your project running in a docker container, then have a makefile command to build your project, maybe something like
.PHONY: up
up:
$(MAKE) down
docker-compose up -d
$(MAKE) logs
With a compose file to setup your project, and then rely on make <insert command> to run / build your project. One command could be make shell to enter a shell environment where all your devs have the same npm / node versions. npm i -g npm#latest is not an answer as that just installs npm on wherever it is run, so new devs will still have to run that command unless its part of the build.
Try to remove package-lock.json and run npm install again.

npm install NOT dowloading latest package

[context]
I have a problem to use "npm install" command to update my package.json with latest dependencies.
I am running on a Jenkins slave with Multibranch Pipeline, not sure if this is the cause?
There is another post having a similar issue, but not been answered ...
NPM package.json not updating after npm install
Here is my package.json
"dependencies": {
"#company/ai-integration-test": "^1.0.1-NIGHTLY",
"#company/ai-portal": "^1.0.1-NIGHTLY",
"#company/ai-portal-lambdas": "^1.0.1-NIGHTLY"
}
Here is the result for "npm outdated"
[What do I expect]
I would like to get my package.json by running some command if "npm install" is the correct command to use? Thanks a million !!
delete your package-lock.json file.
and try npm install again.
But npm install will only update those packages which have "^" in their version, it means auto-update that particular package when you run npm install.
I found npm update command helps me to update package.json to the latest available version. But not sure if I am doing the right things though ... inputs are still welcome !! TKS !!
[Final Answer]
It turns out the problem was caused by our company's IT firewall settings.
The firewall intermittently forge SSL certificate for security reasons.
When that happens, downloading latest package fails without giving error messages.
some of those updates are the major release npm update won't update to the latest version.
The major release does not update in this way because they maybe introduce breaking changes. npm save you from that trouble
npm install -g npm-check-updates
then run it:
ncu -u
this will update all packages to the latest version in the package.json

Make `npm install --save` add a strict version to package.json

When you run npm install --save somepackage, it usually adds something like this into package.json:
"dependencies": {
"somepackage": "^2.1.0"
}
Because the version is prepended with a caret(^), this means that if you later run npm install, it might install version 2.3.0 instead. This can be undesirable for fairly obvious reasons. npm shrinkwrap is useful, but doesn't really solve the problem.
So, I have several questions:
When installing a package, is it possible to specify that you want it to be set to a specific version in package.json (no caret before the version number)?
When publishing a package to npm, is there any way to prevent the default of including the caret before the version when other developers install your package?
To specify by default a exact version, you can change your npm config with save-exact:
npm config set save-exact true
You can also specify the prepend version with a tilde with save-prefix.
And, no you can't force user to update to a minor or a patch version, NPM uses semver and it's the recommend way of publishing packages.
You can change the default behaviour by using the --save-exact option.
// npm
npm install --save --save-exact react
// yarn
yarn add --exact react
I created a blog post about this if anyone is looking for this in the future.
https://www.dalejefferson.com/blog/how-to-save-exact-npm-package-versions/
Run:
npm install --save --save-exact my-module#my-specific-version
Adding an answer to make this advice easier to see.

npm check and update package if needed

We need to integrate Karma test runner into TeamCity and for that I'd like to give sys-engineers small script (powershell or whatever) that would:
pick up desired version number from some config file (I guess I can put it as a comment right in the karma.conf.js)
check if the defined version of karma runner installed in npm's global repo
if it's not, or the installed version is older than desired: pick up and install right version
run it: karma start .\Scripts-Tests\karma.conf.js --reporters teamcity --single-run
So my real question is: "how can one check in a script, if desired version of package installed?". Should you do the check, or it's safe to just call npm -g install everytime?
I don't want to always check and install the latest available version, because other config values may become incompatible
To check if any module in a project is 'old':
npm outdated
'outdated' will check every module defined in package.json and see if there is a newer version in the NPM registry.
For example, say xml2js 0.2.6 (located in node_modules in the current project) is outdated because a newer version exists (0.2.7). You would see:
xml2js#0.2.7 node_modules/xml2js current=0.2.6
To update all dependencies, if you are confident this is desirable:
npm update
Or, to update a single dependency such as xml2js:
npm update xml2js
To update package.json version numbers, append the --save flag:
npm update --save
npm outdated will identify packages that should be updated, and npm update <package name> can be used to update each package. But prior to npm#5.0.0, npm update <package name> will not update the versions in your package.json which is an issue.
The best workflow is to:
Identify out of date packages with npm outdated
Update the versions in your package.json
Run npm update to install the latest versions of each package
Check out npm-check-updates to help with this workflow.
Install npm-check-updates with npm i npm-check-updates -g
Run npm-check-updates to list what packages are out of date (basically the same thing as running npm outdated)
Run npm-check-updates -u to update all the versions in your package.json (this is the magic sauce)
Run npm update as usual to install the new versions of your packages based on the updated package.json
There is also a "fresh" module called npm-check:
npm-check
Check for outdated, incorrect, and unused dependencies.
It also provides a convenient interactive way to update the dependencies with npm-check -u.
One easy step:
$ npm i -g npm-check-updates && ncu -u && npm i
That is all. All of the package versions in package.json will be the latest major versions.
Edit:
What is happening here?
Installing a package that checks updates for you.
Use this package to update all package versions in your package.json (-u is short for --updateAll).
Install all of the new versions of the packages.
To update a single local package:
First find out your outdated packages by:
npm outdated
Then update the package or packages that you want manually as:
npm update --save <package_name>
This way it is not necessary to update your local package.json
file manually.
Note that the above command will update your package to the latest version.
If you write some version in your package.json file and do:
npm update <package_name>
In this case you will get just the next stable version (wanted) regarding the version that you wrote in your package.json file.
And with npm list <package_name> you can find out the current version of your local package.
You can try either of these options:
Check outdated packages
npm outdated
Check and pick packages to update
npx npm-check -u
No additional packages, to just check outdated and update those which are, this command will do:
npm install $(npm outdated | cut -d' ' -f 1 | sed '1d' | xargs -I '$' echo '$#latest' | xargs echo)
NPM commands to update or fix vulnerabilities in some dependency manifest files
Use below command to check outdated or vulnerabilities in your node modules.
npm audit
If any vulnerabilities found, use below command to fix all issues.
npm audit fix
If it doesn't work for you then try
npm audit fix -f, this command will almost fix all vulnerabilities. Some dependencies or devDependencies are locked in package-lock.json file, so we use -f flag to force update them.
If you don't want to use force audit fix then you can manually fix your dependencies versions by changing them in package-lock.json and package.json file. Then run
npm update && npm upgrade
When installing npm packages (both globally or locally) you can define a specific version by using the #version syntax to define a version to be installed.
In other words, doing:
npm install -g karma#0.9.2
will ensure that only 0.9.2 is installed and won't reinstall if it already exists.
As a word of a advice, I would suggest avoiding global npm installs wherever you can. Many people don't realize that if a dependency defines a bin file, it gets installed to ./node_modules/.bin/. Often, its very easy to use that local version of an installed module that is defined in your package.json. In fact, npm scripts will add the ./node_modules/.bin onto your path.
As an example, here is a package.json that, when I run npm install && npm test will install the version of karma defined in my package.json, and use that version of karma (installed at node_modules/.bin/karma) when running the test script:
{
"name": "myApp",
"main": "app.js",
"scripts": {
"test": "karma test/*",
},
"dependencies": {...},
"devDependencies": {
"karma": "0.9.2"
}
}
This gives you the benefit of your package.json defining the version of karma to use and not having to keep that config globally on your CI box.
As of npm#5.0.0+ you can simply do:
npm update <package name>
This will automatically update the package.json file. We don't have to update the latest version manually and then use npm update <package name>
You can still get the old behavior using
npm update --no-save
(Reference)
A different approach would be to first uprade the package.json file using,
ncu -u
and then simply run,
npm install
to update all the packages to the latest version.
ps: It will update all the packages to the latest version however if the package is already up to date that package will not be affected at all.
3 simple steps you can use for update all outdated packages
First, check the packages which are outdated
sudo npm i -g npm-check-updates
Second, put all of them in ready
ncu -u
Results in Terminal will be like this:
Third, just update all of them.
npm install
That's it.
Just do this to update everything to the latest version -
npx npm-check-updates -u
Note - You'll be prompted to install npm-check-updates. Press y and enter.
Now run npm i. You're good to go.
To really update just one package install NCU and then run it just for that package. This will bump to the real latest.
npm install -g npm-check-updates
ncu -f your-intended-package-name -u
You can do this completely automatically in 2022
Install npm-check-updates
Run the command
ncu --doctor -u
It will first try every dependency you have and run tests, if the tests fail it will update each dependency one by one and run tests after each update
One more for bash:
npm outdated -parseable|cut -d: -f5|xargs -L1 npm i
I'm just interested in updating the outdated packages using the semantic versioning rules in my package.json.
Here's a one-liner that takes care of that
npm update `npm outdated | awk '{print $1}' | tr '\n' ' '`
What it does:
takes the output from npm outdated and
pipes that into awk where we're grabbing just the name of the package (in column 1)
then we're using tr to convert newline characters into spaces
finally -- using backticks -- we're using the output of the preceding steps as arguments to npm update so we get all our needed updates in one shot.
One would think that there's a way to do this using npm alone, but it wasn't here when I looked, so I'm just dropping this here in case it's helpful to anyone 😀.
** I believe there's an answer that MikeMajara provides here that does something similar, but it's appending #latest to the updated package name, which I'm not really interested in as a part of my regularly scheduled updates.
If you want to upgrade a package to the latest release, (major, minor and patch), append the #latest keyword to the end of the package name, ex:
npm i express-mongo-sanitize#latest
this will update express-mongo-sanitize from version 1.2.1 for example to version 2.2.0.
If you want to know which packages are outdated and which can be updated, use the npm outdated command
ex:
$ npm outdated
Package Current Wanted Latest Location Depended by
express-rate-limit 3.5.3 3.5.3 6.4.0 node_modules/express-rate-limit apiv2
helmet 3.23.3 3.23.3 5.1.0 node_modules/helmet apiv2
request-ip 2.2.0 2.2.0 3.3.0 node_modules/request-ip apiv2
validator 10.11.0 10.11.0 13.7.0 node_modules/validator apiv2
If you have multiple projects with the same node-modules content, pnpm is recommended. This will prevent the modules from being downloaded in each project. After the installation the answer to your question is:
pnpm up

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

I have this in my package.json file (shortened version):
{
"name": "a-module",
"version": "0.0.1",
"dependencies": {
"coffee-script": ">= 1.1.3"
},
"devDependencies": {
"stylus": ">= 0.17.0"
}
}
I am using NPM version 1.1.1 on Mac 10.6.8.
When I run the following command from the project root, it installs both the dependencies and devDependencies:
npm install
I was under the impression that this command installed the devDependencies:
npm install --dev
How do I make it so npm install only installs dependencies (so production environment only gets those modules), while something like npm install --dev installs both dependencies and devDependencies?
The npm install command will install the devDependencies along other dependencies when run inside a package directory, in a development environment (the default).
In version 8.x and above use --omit=dev flag to install only regular dependencies:
npm install --omit=dev
This will install only dependencies, and not devDependencies, regardless of the value of the NODE_ENV environment variable.
If you use 6.x or an earlier version, you need to use the --only=prod flag instead.
Note:
Before v3.3.0 of npm (2015-08-13), the option was called --production, i.e.
npm install --production
You may also need --no-optional flag.
I run into that problem too! npm install is somewhat confusing and web posts keep bringing in the -d/--dev flags as if there is an explicit 'development' install mode.
npm install will install both "dependencies" and "devDependencies"
npm install --production will only install "dependencies"
npm install --dev will only install "devDependencies"
The new option is:
npm install --only=prod
If you want to install only devDependencies:
npm install --only=dev
If you have already installed all your dependencies, and you want to avoid having to download your production packages from NPM again, you can simply type:
npm prune --production
This will remove your dev dependencies from your node_modules folder, which is helpful if you're trying to automate a two step process like
Webpack my project, using dev dependencies
Build a Docker image using only production modules
Running npm prune in between will save you from having to reinstall everything!
If you read this POST in 2016, please achieve what you want by using
--only={prod[uction]|dev[elopment]}
argument will cause either only devDependencies or only non-devDependencies to be installed regardless of the NODE_ENV.
from: https://docs.npmjs.com/cli/install
When using "npm install" the modules are loaded and available throughout your application regardless of if they are "devDependencies" or "dependencies". Sum of this idea: everything which your package.json defines as a dependency (any type) gets installed to node_modules.
The purpose for the difference between dependencies/devDependencies/optionalDependencies is what consumers of your code can do w/ npm to install these resources.
Per the documentation: https://npmjs.org/doc/json.html...
If someone is planning on downloading and using your module in their
program, then they probably don't want or need to download and build
the external test or documentation framework that you use.
In this case, it's best to list these additional items in a
devDependencies hash.
These things will be installed whenever the --dev configuration flag
is set. This flag is set automatically when doing npm link or when
doing npm install from the root of a package, and can be managed like
any other npm configuration param. See config(1) for more on the
topic.
However, to resolve this question, if you want to ONLY install the "dependencies" using npm, the following command is:
npm install --production
This can be confirmed by looking at the Git commit which added this filter (along with some other filters [listed below] to provide this functionality).
Alternative filters which can be used by npm:
--save => updates dependencies entries in the {{{json}}} file
--force => force fetching remote entries if they exist on disk
--force-latest => force latest version on conflict
--production => do NOT install project devDependencies
--no-color => do not print colors
#dmarr try using npm install --production
npm will install dev dependencies when installing from inside a package (if there is a package.json in the current directory). If it is from another location (npm registry, git repo, different location on the filesystem) it only installs the dependencies.
I suggest to use npm ci. If you want to install only production-needed packages (as you wrote - without devDependencies) then:
npm ci --only=production
or
NODE_ENV=production npm ci
If you prefer oldschool npm install then:
npm install --production
or
NODE_ENV=production npm install
Here is good answer why you should use npm ci.
It's worth mentioning that you can use the NODE_ENV environment variable to achieve the same result. Particularly useful if you're containerizing your Node application (e.g. Docker).
NODE_ENV=production npm install
The above code will install all your dependencies but the dev ones (i.e. devDependencies).
if you need to use environment variables in your Dockerfile more information can be found here.
Environment variables are easy to overwrite whenever needed (e.g. if you want to run your test suite say on Travis CI). If that were the case you could do something like this:
docker run -v $(pwd):/usr/src/app --rm -it -e NODE_ENV=production node:8 npm install
NPM Documentation here
production
Default: false
Type: Boolean
Set to true to run in "production" mode.
devDependencies are not installed at the topmost level when running local npm install without any arguments.
Set the NODE_ENV="production" for lifecycle scripts.
Happy containerization =)
npm install --production --no-optional
It installs only deps from dependencies and will ignore optionalDependencies and devDependencies
Use npm install packageName --save this will add package in dependencies, if you use npm install packageName --save-dev then it devDependencies.
npm install packageName --save-dev should be used for adding packages for development purpose. Like adding TDD packages (Chai, mocha, etc). Which are used in development and not in production.
I have found that, when trying to install dev dependencies for a package that contains a node addon, you cannot avoid building the addon when running npm install --dev even if you just want to install the devDependencies. So, I had to go around npm's back:
node -e 'console.log( Object.keys( require( "./package.json" ).devDependencies ) );' | \
sed -e "s/^[^']*'//" -e "s/'.*$//" | \
xargs npm install
Or, better (and more succinctly) yet,
node -e 'Object.keys( require( "./package.json" ).devDependencies )
.map( function( item ){ console.log( item ) } );' | xargs npm install
I ran into a problem in the docker node:current-slim (running npm 7.0.9) where npm install appeared to ignore --production, --only=prod and --only=production. I found two work-arounds:
use ci instead (RUN npm ci --only=production) which requires an up-to-date package-lock.json
before npm install, brutally edit the package.json with:
RUN node -e 'const fs = require("fs"); const pkg = JSON.parse(fs.readFileSync("./package.json", "utf-8")); delete pkg.devDependencies; fs.writeFileSync("./package.json", JSON.stringify(pkg), "utf-8");'
This won't edit your working package.json, just the one copied to the docker container.
Of course, this shouldn't be necessary, but if it is (as it was for me), there's your hack.
Need to add to chosen answer: As of now, npm install in a package directory (containing package.json) will install devDependencies, whereas npm install -g will not install them.
npm install --production is the right way of installing node modules which are required for production. Check the documentation for more details
Now there is a problem, if you have package-lock.json with npm 5+. You have to remove it before use of npm install --production.

Resources