NPM problems with multiple node versions
Published 2019-8-8For the times when you want all scripts and subscripts executed by npm to be executed with the same node version as was used to execute npm:
npm set scripts-prepend-node-path true
Sorry, that was a mouthful... but I don't know how else to say it. Kinda weird, eh?
Anyway, that will update your .npmrc accordingly:
.npmrc
:
scripts-prepend-node-path=true
And if you need it in a scripting environment, you can use it as an option to npm directly:
npm --scripts-prepend-node-path=true run your-script-name
In particular, this applies to the scripts section of your package.json:
{
"scripts": {
"dostuff": "node ./scripts/your-script-name.js"
}
}
Basically what this does is prepend the node described by process.args[0]
and prepends it to the PATH for any child scripts.
For example:
export PATH="/opt/your-bundled-app/bin:${PATH}"
Note that the change to the environment only applies to child processes of the npm scripts, and does not affect the shell from which you run the npm script (that's a security feature of pretty much all shells).
Backstory
I build a lot of developer-oriented CLI and system tools in node, but they're not always node-related.
As such, I don't always expect that the users of these tools will have node installed.
Similarly, just because they have a version of node installed doesn't mean that it's the right version of node for my tool (and some of them have relied on lesser-used APIs that have had crippling bugs in some node versions).
To solve for that, I sometimes create an installer that installs node first, or I'll create a zip file or tarball that bundles node and is ready-to-rock once unpacked, moved into the target directory, and added to the path.
However, this creates another problem - if the user does have node install,
any scripts called by npm will use node
from the user's current PATH, rather
than the one in the package! Maddening.
Anyway, that's where scripts-prepend-node-path
comes in.
For most people, a better way to do what I'm doing (self-contained, isolated node apps)
is probbaly to use either warp
or Zeit's pkg
,
but I am a peculiar man and I've
got my own reasons why I do what I do
By AJ ONeal
Did I make your day?
Buy me a coffee
(you can learn about the bigger picture I'm working towards on my patreon page )