Automatically use the right version of Node for a package

1k Views Asked by At

I know it is possible to switch between different versions of Node using NVM, n, or similar.

Is there a convenient way for the right version of Node to automatically be used when running commands within a given package? ("Right version" being determined by the engine tag or similar).

For instance, I would like to be able to do this:

cd mypackage-that-needs-node10
npm run serve
# ... node 10 is used
cd ..
cd mypackage-that-needs-node14
npm run serve
# ... node 14 is used
2

There are 2 best solutions below

2
shadowspawn On BEST ANSWER

n supports an engine label to find Node.js version from package.json, and auto which includes more sources such as a .node-version file.

For example:

$ n install engine
# or run the target version of node
$ n run auto index.js
# or execute a command with that Node.js in path
$ n exec auto npm run serve
0
shadowspawn On

A possible approach is to install node itself into your package, and have npm run scripts use it in preference to the system version of node. See node