Skip to content

Instantly share code, notes, and snippets.

@ppeelman
Last active November 24, 2022 09:04
Show Gist options
  • Save ppeelman/d17f67ff15c39966279dd62cf11f02df to your computer and use it in GitHub Desktop.
Save ppeelman/d17f67ff15c39966279dd62cf11f02df to your computer and use it in GitHub Desktop.
Switch Node version automatically using package.json(engines) or .nvmrc or .node-version
# place this after nvm initialization!
autoload -U add-zsh-hook
load-nvmrc() {
local node_version="$(nvm version)"
local nvmrc_path="$(nvm_find_nvmrc)"
# Get node version from package.json engines section (remove 'v' if present)
local package_json_node_version="$([ -r package.json ] && cat package.json | jq '.engines.node' --raw-output)"
if [ "$package_json_node_version" != "null" ] && [[ ! -z "$package_json_node_version" ]]; then
echo "Found package.json engines section with node version $package_json_node_version. This takes precedence over .nvmrc"
local nvmrc_node_version_from_engines=$(nvm version "$package_json_node_version")
if [ "$nvmrc_node_version_from_engines" = "N/A" ]; then
nvm install "$package_json_node_version"
elif [ "$package_json_node_version" != "$node_version" ]; then
nvm use "$package_json_node_version"
fi
elif [ -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
@ppeelman
Copy link
Author

TODO: check .node-version file (package.json > .nvmrc > .node-version)

@ppeelman
Copy link
Author

If you use Bash, do the following to have a similar 'hook' system: https://gist.github.com/laggardkernel/6cb4e1664574212b125fbfd115fe90a4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment