问题
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!
回答1:
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){
....
}
}
回答2:
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.
回答3:
I would encourage you to take a different tack on uglifying your code. Take a look at connect-browserify or the even more powerful asset-rack.
These can automatically uglify your code on launch of the Express server, rather than on install. And you can configure them to do different things in development and production.
来源:https://stackoverflow.com/questions/18766678/running-npm-scripts-conditionally