When deploying to Modulus.io (this probably applies to other PAAS as well), they will install the required packages from the packages.json file. As part of the install process, some npm scripts might be called as well. For example postinstall
. However, these scripts might not be able to run (or should not run) on production. Be it because of scripts that are only available locally or do not make any sense on production.
How can I detect the environment and execute or not execute certain npm scripts? Can I access the process.env
object and handle the scripts appropriatly or is there a better way?
Unfortunately, you can't in your package.json
define script only for specific environment.
Let's say you have a postinstall
script declared like this in package.json
:
{
"scripts": {
"postinstall": "node postInstall.js"
},
}
The "easy" way would be to add your logic regarding the environment in this postInstall.js
script:
if (process.env.NODE_ENV === 'production') {
// Do not run in production
process.exit(1);
}
If you're running in the production
environment, you just instructs Node.js to terminate the process as quickly as possible with the specified exit code for example.
You could also if you're running multiple scripts in the postinstall
hook, move all your scripts execution in a wrapper having the same mechanism to exit on certain environment, if not, executes all the other scripts.
Another approach if you're always running on Unix systems is to check directly the Node.js environment using a Bash condition:
{
"scripts": {
"postinstall": "[ \"$NODE_ENV\" != production ] && node postInstall.js"
},
}
In this case, if the node environment is not production
, then you're running your postInstall.js
script. You can adjust it to other conditions like only in development
, etc.