Specify Node.js version for npm script execution

I’m trying to run my project with a particular Node.js version using npm scripts. Is there a way to tell npm which Node executable to use when I type npm run dev?

Here’s what I’ve tried so far:

# In package.json
"scripts": {
  "dev": "NODE_PATH=/path/to/node myapp serve"
}

But it doesn’t seem to work. The tricky part is that my dev script actually calls a CLI tool (let’s call it myapp). So whatever solution we find needs to work with that too.

I also looked into the .npmrc file, but couldn’t find any options there. Any ideas on how to make this work? It would be super helpful for keeping my dev environment consistent.

I’ve faced a similar issue before, and I found that using the ‘npx’ command can be quite effective for specifying Node versions. You could modify your script to something like this:

“dev”: “npx -p node@ myapp serve”

Replace with the specific Node version you need. This approach uses npx to temporarily install and use the specified Node version for running your script.

Another option is to use a version manager like ‘nvm’. You can set up a .nvmrc file in your project root with the desired Node version, then update your script to:

“dev”: “nvm use && myapp serve”

This ensures the correct Node version is active before running your CLI tool. Both methods should work well with external tools like ‘myapp’.

hey, have u tried using the cross-env package? it’s pretty neat for this kinda stuff. you can install it and then modify ur script like this:

“dev”: “cross-env NODE_PATH=/path/to/node myapp serve”

it should work across different platforms too. worth a shot!

I’ve actually encountered this issue in a production environment, and we solved it using a combination of nvm (Node Version Manager) and a custom shell script. Here’s what we did:

First, we created a shell script (let’s call it run-with-node.sh) that looked something like this:

#!/bin/bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
nvm use <specific-node-version>
exec "$@"

Then, in our package.json, we modified the script to use this shell script:

“dev”: “./run-with-node.sh myapp serve”

This approach ensures that the correct Node version is used for both the npm script and the CLI tool. It’s a bit more setup, but it gave us the flexibility and consistency we needed across our team and CI/CD pipeline.