Last active
December 7, 2021 22:44
-
-
Save cesalazar/976163e198985d0d5912eb6512126ba8 to your computer and use it in GitHub Desktop.
Automatically changes NodeJS version using `n` node package in zsh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# hooks onto `chpwd` with the official util `add-zsh-hook` | |
# `export N=false` to disable auto-switching versions | |
function auto-switch-node-version() { | |
# track if the version changed | |
local changed=false | |
# exit early | |
[[ ${N} == false || ! $(command -v n) ]] && return | |
# attempt to change the version based on the "engine" entry in package.json | |
n engine &>/dev/null && changed=true | |
# fallback to .nvmrc file if it exists | |
[[ ${changed} == false && -f .nvmrc ]] && n auto &>/dev/null && changed=true | |
# give up and write a log if the folder is a node project :( | |
[[ ${changed} == false && -f package.json ]] && printf "%s\n" \ | |
"Missing \"engine\" entry in package.json" \ | |
"File .nvmrc not found" \ | |
"Falling back to node $(node -v) and npm v$(npm -v)" \ | |
>! n.log | |
} | |
# switch node version automatically on new session | |
auto-switch-node-version | |
# load add-zsh-hook if it's not available yet | |
(( $+functions[add-zsh-hook] )) || autoload -Uz add-zsh-hook | |
# hook auto-switch-node-version onto `chpwd` | |
add-zsh-hook chpwd auto-switch-node-version | |
# list existing hook functions | |
# add-zsh-hook -L |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment