I enjoy using the very latest version of node.js for my quick scripts I write on my computer. That means that my nvm is set to run Node v14. Every time I’ve fired up our egghead-next project recently, I’ve had to switch to Node.js v12 (the latest stable version) to run yarn dev
. I was getting sick of running nvm use 12
every time I opened a shell, so I set out to see what I could do.
It turns out that zsh has a precmd “hook” that allows you to run some code each time you open a new prompt. That gave me an idea to check my current Node version against the Node version listed in the package.json.
The hook is a function living inside of my .zshrc file.
You will need to install jq for this function since I use it to read the “engines” field on the package.json.
The script reads like this:
- If a
package.json
exists - set the
nodeVersion
to the.engines.node
field - if
nodeVersion
exists and nvm isn’t set to that version nvm use
the first two characters ofnodeVersion
precmd(){if [ -f package.json ]thennodeVersion=$(jq -r '.engines.node | select(.!=null)' package.json )if [ ! -z $nodeVersion ] \&& [[ ! $(nvm current) = "^v$nodeVersion" ]]thenecho "found $nodeVersion in package.json engine"nvm use ${nodeVersion:0:2}fifi}
Now this just runs in the background each time a new prompt fires up and I never have to think about it again! 🎉
Of note, JRGould also shared his script with me where he’s checking against .nvmrc files. Definitely worth considering this approach too!
Game changer when switching between a lot of projects. I use the `chpwd` hook which runs whenever you `cd` or `z` or `j` or `..` or whathaveyou into a new dir. Also some fancyness to use .nvmrc and install the required version if I don't already have it.pic.twitter.com/R6GHNrudHz
— Jeff Gould (@JRGould) September 14, 2020