Running npm scripts conditionally

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){
    ....
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)