check if a .env variable is x in npm scripts

2.7k views Asked by At

So I am looking to create a script in the package.json that runs either start:dev or start:prod if ENV in the .env file is set to dev or prod and by default - if nothing is set start:dev should run.

I am unsure how to check environment variables inside a npm run script.

What I want

Something like:

if ENV === dev 
  yarn start:dev 
else if ENV === prod 
  yarn start:prod 
else 
  yarn start:dev

Any ideas?

1

There are 1 answers

2
EMX On BEST ANSWER

This is the if/elif/else you are looking for : (extrapolate this example to your own needs)

#!/usr/bin/env bash
if [ "$ENV" = "DEV" ]
then
    echo "Development Mode"
elif [ "$ENV" = "PROD" ]
then
    echo "Production Mode"
else
    echo "ENV : has not been set yet..."
fi

Its possible to then use the .sh from the package.json scripts (example) :

"scripts": {"start": "./checkEnv.sh"}

... dont forget permissions : chmod +x ./checkEnv.sh