TL;DR: Is there a way to have npm install run automatically before running any npm script if your package.json has been modified?
Like other answers, but I think simpler because it's one line of shell script in package.json:
{
"scripts": {
"install-if-needed": "[ package.json -nt node_modules ] && npm install && touch node_modules",
"my-script": "npm run install-if-needed && ..."
}
}
or, basically equivalent:
{
"scripts": {
"install-if-needed": "[ package.json -nt node_modules ] && npm install && touch node_modules",
"premy-script": "npm run install-if-needed",
"my-script": "..."
}
}
You'll have to either inline npm run install-if-needed or have a pre... script for each script that needs it -- I don't know any other way to have it run before multiple other scripts.
Explanation: install-if-needed checks the modification times on package.json and node_modules. If node_modules is newer, it does nothing; otherwise it runs npm install. The final touch node_modules is necessary because npm install may itself change the package.json modification time (if it is correcting whitespace in package.json for example).