nvm, based on the presence of a
It works pretty well, but where I work we already specify Node version constraints in our
package.jsonfiles (under the
engineskey) and weren't keen on duplicating that information, since said constraints mostly consist of a strict version anyway. I therefore adapted the original script to read from there instead:
autoload -U add-zsh-hook
if [[ -f package.json ]] && grep -q '"node"' package.json; then
nvm use `cat package.json | sed -nE 's/"node": "[^0-9]*([0-9\.]*)[^"]*"/\1/p'`
elif [[ $(nvm version) != $(nvm version default) ]]; then
nvm use default
add-zsh-hook chpwd switch-node-version
When using a range (e.g.
>=10 <14, etc.), special characters are dropped (which would result in
nvm use 10with the latter example). This brings one caveat, which is that the script doesn't play nice with overly specific ranges, such as
^10.0.0: it would indeed try to
nvm use 10.0.0, and that particular version might not be available on one's machine. In such cases, I would advise shortening the range to
^10(which better conveys the idea anyway in my opinion).