How to upgrade all global NPM packages to their latest non-breaking version?

Viewed 28

I try to update all global packages (including NPM itself) to their latest version of their current major version (so current_major.x.x).

npm upgrade -g --force will forcefully upgrade all global packages, including major versions, but this will break things for sure.

Is there a way? I know that I can upgrade all individual packages knowing their current major version, but I'd like to automate the process.

1 Answers

This will do it for me, although, it will re-install existing packages, even when there was no version change.

npm_global_packages=($(npm list -g --depth 0 | awk '/ /{print $2}'))
for val in "${npm_global_packages[@]}"; do
    npm i -g --force $(echo $val | tr "." "\n" | head -1)
done

The --force option is to avoid symlink issues. Leaving it away will not solve unnecessary re-installs. I wonder if there is a smarter way, but that's what I will go for as of now.

In depth

  • npm_global_packages will be an array such as npm@6.14.12 npx@10.2.2 pm2@5.2.0 rimraf@3.0.2.
  • tr "." "\n" | head -1 will split each value by . and return only the first segment, so the script essentially would run npm i -g --force npm@6, npm i -g --force npx@10, ...
Related