# nvm check when zsh initializing autoload -U add-zsh-hook load-nvmrc() { local node_version="$(nvm version)" local nvmrc_path="$(nvm_find_nvmrc)"
if [ -n "$nvmrc_path" ]; then local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")
if [ "$nvmrc_node_version" = "N/A" ]; then nvm install elif [ "$nvmrc_node_version" != "$node_version" ]; then nvm use fi elif [ "$node_version" != "$(nvm version default)" ]; then echo "Reverting to nvm default version" nvm use default fi } add-zsh-hook chpwd load-nvmrc load-nvmrc
# nvm check when running cd command cd-nvm() { builtin cd "$@" if [[ -f .nvmrc ]]; then load-nvmrc fi } alias cd='cd-nvm'
# changes take effect source ~/.bash_profile
■ 以上脚本实现了”从项目目录直接打开命令行”和”通过 cd 命令进入项目目录”两种情况下自动切换 node 到 nvm 默认版本或”.nvmrc”文件指定版本。