Running npm scripts conditionally

25,559

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

Solution 2

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 envs you might do:

"scripts": {
    "build":"node -e \"if (process.env.NODE_ENV === 'production'){process.exit(1)} \" || make install"
}

Solution 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.

Solution 4

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.

Share:
25,559
Protostome
Author by

Protostome

Interested in the intersection of Biology, CS and engineering

Updated on October 06, 2021

Comments

  • Protostome
    Protostome over 2 years

    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!