简体   繁体   中英

Mac/Homebrew - changing Node version does not change NPM version

On my Mac, I'd like to use Homebrew to install an earlier version of Node and NPM - I'm currently running Node/NPM 8.2.1/5.3.0 , and I'd like to switch to 6.11.2/3.10.10 , as listed in the documentation .

I ran

$ brew install node@6
$ brew unlink node
$ brew link node@ --force

and while this appears to change my node version - $ node -v -> 6.11.2 - my version of NPM is still stuck at 5.3.0 .

How can I switch NPM to this other version (and switch it back, if need be)?

Try to uninstall all node versions firstly: brew rm node , after that ensure that node -v and npm -v prints command not found .

After that install nvm or n to manage node versions. These version managers have one great advantage, they allow you to have a few node versions and easily switch between them.

With nvm:

nvm install v6.11.2

Luckily there is a good way to do this if you are someone like myself who finds nvm to be overkill, especially if you only need one version for an app/api support (eg johnny-five). Instead of installing a node version manager, you can actually create a 2nd "node" version with another homebrew node.js install.

Start by installing the other version of node that you want to use, for instance node@4, and then unlink that version's symlinks (you can use any brew installed version).

$ brew install node@4 && brew unlink node@4

Once it's installed and unlinked, go to the folder /usr/local/bin, and add a custom symlink for the other version you want access:

$ cd /usr/local/bin
$ ln -s ../Cellar/node\@4/4.8.5/bin/node ./node4

Now you can use the command node for your previous version, and node4 for the node@4 version.

Of course we do not want to mix npm packages with the two versions, so let's fix that by making a new npm directory for the node@4 version:

$ mkdir ~/.npm4
$ npm config set prefix ~/.npm4

Now you are ready to install global packages for the second version! Each time you want to switch versions you can simply swap the prefix, and since we are looking for a simple process this probably won't happen too often.

Of course you may want something that does not require the need to be proactive when switching versions, and while you can always install a separate version of npm somewhere and symlink it the same way you did the node version, that may become confusing over time when it comes to upgrading npm.

A few other options:

  • script the prefix command
  • add the prefix command and/or script in package.json
  • use a specific bash terminal profile that runs the prefix command on start

So there are few various options, but I will leave that all up to you..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM