curl -o- [<https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh>](<https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh>) | bash
wget -qO- <https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh> | bash
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \\. "$NVM_DIR/nvm.sh" # This loads nvm
在项目的根目录下添加 .nvmrc 文件,并在 .nvmrc 文件中声明 node 版本
# place this after nvm initialization!
autoload -U add-zsh-hook
load-nvmrc() {
# 获取当前 node 版本
local node_version="$(nvm version)"
# 在当前工作目录下寻找 .nvmrc 文件
local nvmrc_path="$(nvm_find_nvmrc)"
if [ -n "$nvmrc_path" ]; then
# 使用 .nvmrc 文件中声明的 node 版本
local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")
# 判断是否安装了对应的 node 版本
if [ "$nvmrc_node_version" = "N/A" ]; then
nvm install
elif [ "$nvmrc_node_version" != "$node_version" ]; then
nvm use
fi
# 如果没有找到 .nvmrc 文件,使用 nvm 中配置的 default 版本
elif [ "$node_version" != "$(nvm version default)" ]; then
echo "Reverting to nvm default version"
nvm use default
fi
}
# zsh chpwd hook 当工作目录发生变化时自动运行 load-nvmrc 函数
add-zsh-hook chpwd load-nvmrc
load-nvmrc
建议将代码添加到 .zshenv 中。
.zshrc 为用户环境变量配置,只有在启动新的交互式 Shell 前会自动加载 .zshenv 为全局环境变量配置,无论是交互式或非交互式 Shell 启动前都会加载
zsh hook: