I have 2 main build configurations - dev and prod. I push updates to a heroku server that run npm install --production to install my app. In the package.json I have the following segment:
"scripts": {
"postinstall": "make install"
}
that runs a make file that is responsible for uglifying the code and some other minor things.
However, I don't need to run this makefile in development mode. Is there any way to conditionally run scripts with npm?..
Thanks!
You can have something like this defined in your package.json
(I'm sure theres a better shorthand for the if
statement.)
"scripts": {
"postinstall":"if test \"$NODE_ENV\" = \"production\" ; then make install ; fi "
}
Then when you execute npm
with production flag like you stated you already do
npm install --production
it will execute your make install
because it will set $NODE_ENV = production
When I need to conditionally execute some task(s), I pass environment variables to the script/program and which takes care of that logic. I execute my scripts like this
NODE_ENV=dev npm run build
and in package.json
, you would start a script/program
"scripts": {
"build":"node runner.js"
}
which would check the value of the environment variable to determine what to do. In runner.js
I do something like the following
if (process.env.NODE_ENV){
switch(process.env.NODE_ENV){
....
}
}
For future reference.
For conditional npm scripts, you can use cross-platform basic logical operators to create if-like statements ( ||
and &&
).
I've run into needing to run scripts to only generate helpers once on any machine. You can use inline javascript to do this by using process.exit()
codes.
"scripts": {
"build":"(node -e \"if (! require('fs').existsSync('./bin/helpers')){process.exit(1)} \" || npm run setup-helpers) && npm run final-build-step"
}
So for testing env
s you might do:
"scripts": {
"build":"node -e \"if (process.env.NODE_ENV === 'production'){process.exit(1)} \" || make install"
}
Can't you add another section in your .json under devDependencies? Then if you do npm install it'd install the packages specified under devDependincies and npm install --production would install the regular dependcies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With