nvm Node Version Manager
切换Node版本
$ nvm list v8.17.0 -> v10.16.0 v12.22.6 system $ nvm use 12.22.6 Now using node v12.22.6 (npm v6.14.15)
使用 .nvmrc
切换Node版本
在目录下创建文件.nvmrc
, 指定node的版本
$ echo '12.22.6' > .nvmrc
切换Node版本
$ nvm use Now using node v12.22.6 (npm v6.14.15)
自动调用 nvm use
MacOS中在~/.bash_profile
文件中添加一下代码段:
添加如下代码
## Automatically call nvm use cdnvm() { command cd "$@"; nvm_path=$(nvm_find_up .nvmrc | tr -d '\n') # If there are no .nvmrc file, use the default nvm version if [[ ! $nvm_path = *[^[:space:]]* ]]; then declare default_version; default_version=$(nvm version default); # If there is no default version, set it to `node` # This will use the latest version on your machine if [[ $default_version == "N/A" ]]; then nvm alias default node; default_version=$(nvm version default); fi # If the current version is not the default version, set it to use the default version if [[ $(nvm current) != "$default_version" ]]; then nvm use default; fi elif [[ -s $nvm_path/.nvmrc && -r $nvm_path/.nvmrc ]]; then declare nvm_version nvm_version=$(<"$nvm_path"/.nvmrc) declare locally_resolved_nvm_version # `nvm ls` will check all locally-available versions # If there are multiple matching versions, take the latest one # Remove the `->` and `*` characters and spaces # `locally_resolved_nvm_version` will be `N/A` if no local versions are found locally_resolved_nvm_version=$(nvm ls --no-colors "$nvm_version" | tail -1 | tr -d '\->*' | tr -d '[:space:]') # If it is not already installed, install it # `nvm install` will implicitly use the newly-installed version if [[ "$locally_resolved_nvm_version" == "N/A" ]]; then nvm install "$nvm_version"; elif [[ $(nvm current) != "$locally_resolved_nvm_version" ]]; then nvm use "$nvm_version"; fi fi } alias cd='cdnvm' cd "$PWD"
添加指令
$ vim ~/.bash_profile # 添加完后让其生效 $ source ~/.bash_profile
每次进入目录后,就会自动切换到指定的Node版本了
Now using node v12.22.6 (npm v6.14.15)
参考
https://github.com/nvm-sh/nvm#bash