How to run global npm packages when changing node.js version using nvm?
nvm
stands for Node Version Manager. It is a tool used to manage multiple versions of Node.js on a single machine. With nvm
, developers can easily switch between different versions of Node.js, which is useful for testing and running projects that require specific Node.js versions.
When you use a specific Node.js version for a brief period, you probably have installed a few global npm packages so they can be accessed from anywhere on your machine.
But if you run any global npm packages (i.e., nodemon, tsc, etc.) after changing your Node.js version via nvm
(example, nvm install <version>
or nvm use <version>
), you will get a command not found or similar message.
This happens because nvm
maintains separate directories for global packages for each Node.js version. Switching versions with nvm use <version>
changes the active Node.js version, but not the global packages associated with that version.
The Solution
nvm
has two similar commands to reinstall the global packages from the previous version.
Solution #1
If you have already changed your desired Node.js version without installing the global packages, then you can run the following command:
nvm reinstall-packages <old-version>
Replace <old-version>
with the previous Node.js version. This command reinstalls the globally installed packages from the old version to the new one.
Solution #2
This next command is particularly useful when you want to switch Node.js versions and ensure that the same set of global packages is available in the new version.
nvm install <new-version> --reinstall-packages-from=<old-version>
<new-version>
: The version of Node.js you want to install.<old-version>
: The version of Node.js from which you want to reinstall the global packages.
So there you have it, by understanding how nvm
manages global packages and using these methods, you can ensure that your global npm packages are available regardless of the Node.js version you are using.