作為前端開發者,node和npm安裝必不可少。然而有時會因為安裝新的app(如MacPorts,慎裝,它會修改基本環境變量以及npm的全局設置等)導致版本環境混亂,有2種方式有效管理:
- 特別推薦安裝安裝nvm來管理Node版本;
- 其次推薦brew來對node和npm版本進行管理。
(首選)nvm管理Node
目前我更多的使用nvm來進行node版本管理,它會安裝相應版本的npm。
執行如下命令:
- 安裝nvm
curl -L -o- [http://build.sankuai.com/nvm/install](http://build.sankuai.com/nvm/install) | bash
上述失敗了的話試試這個:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash
上述再失敗了的話試試這個:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash
nvm 常用命令
- nvm install xxx ???? //安裝xxx版本號
- nvm use xxx ?????? //設置使用xxx版本號
- nvm ls ???????? //所有已安裝的node版本號
- nvm alias default v10.16.0 //nvm設置默認node版本號
- 安裝node及npm
nvm install v8.5.0
- 將鏡像源設置為淘寶鏡像
export NVM_NODEJS_ORG_MIRROR=https://npm.taobao.org/mirrors/node
npm --registry=https://registry.npm.taobao.org
安裝brew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew安裝node
- 首先更新brew,使其在最新版本,代碼如下:
$ brew update
- 確保brew是安全可靠的,代碼如下:
$ brew doctor
將可能導致如下情況,可針對性逐條處理,處理完成放可完成下一步:
Warning: Some directories in /usr/local/share/man aren't writable.
This can happen if you "sudo make install" software that isn't managed
by Homebrew. If a brew tries to add locale information to one of these
directories, then the install will fail during the link step.You should probably
sudo chown -R $(whoami)
them:
/usr/local/share/man/man5
/usr/local/share/man/man7
- 將brew的位置添加到
PATH"`
- 當處理完上述問題后,來處理brew和node關系
若在上文中出現,如下錯誤信息:
Warning: You have unlinked kegs in your Cellar
Leaving kegs unlinked can lead to build-trouble and cause brews that depend on
those kegs to fail to run properly once built. Runbrew link
on these:
node
則需要如下操作:
- 清理brew的link
$ brew cleanup
- 刪除node文件,完全卸載node和npm
sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}
或者是
sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* /usr/local/lib/dtrace/node.d ~/.npm ~/.node-gyp /opt/local/bin/node opt/local/include/node /opt/local/lib/node_modules
或者是下面這樣:
1.在/usr/local/lib目錄下,刪除任何與node和 node_modules有關的目錄;
2.在/usr/local/include 目錄下,刪除任何與node 和 node_modules有關的目錄;
3.如果你是通過**brew install node**安裝的node,則在終端執行**brew uninstall node** ,并在home目錄下查找 **local** 或**lib** 或 **include**文件夾,刪除任何與**node** 和 **node_modules**有關的目錄;
4.在**/usr/local/bin**目錄下,刪除任何與 **node** 執行文件;
5.最后下載 **nvm** ,跟隨它的介紹安裝node。當然,你也可以通過**npm**來安裝最新版本的Node。
- 通過brew安裝node和npm
brew link node
brew uninstall node
brew install node
- 測試Node和npm安裝是否成功,安裝Grunt
npm install -g grunt-cli
如果安裝成功,那么恭喜你node,npm,grunt均安裝成功。若出現問題,請回顧前面內容。