ENV setup and `mongo run` in npm scripts

I have some npm scripts to run meteor run with ENV setup:

{
  "scripts": {
    "start": "MONGO_URL=mongodb://account:password@host:port/database meteor run",
    "ios": "MONGO_URL=mongodb://account:password@host:port/database meteor run ios",
    "android": "MONGO_URL=mongodb://account:password@host:port/database meteor run android",
    "ios-android": "MONGO_URL=mongodb://account:password@host:port/database meteor run ios android",
    // ... and so on
  }
}

Now I need to add MAIL_URL ENV to run meteor, I wand to extract those ENV setup into a separated npm script with export for Don’t-Repeat-Yourself, and call it before meteor run:

{
  "scripts": {
    "env": "export MONGO_URL=mongodb://account:password@host:port/database && export MAIL_URL=smtp://USERNAME:PASSWORD@HOST:PORT",
    "start": "npm run env && meteor run",
    "ios": "npm run env && meteor run ios",
    "android": "npm run env && meteor run android",
    "ios-android": "npm run env && meteor run ios android",
    // ... and so on
  }
}

But it failed to set up the ENV variables in meteor with these script. I tried to print the MONGO_URL in Meteor.startup and it shows local MONGO_URL:

Meteor.startup(() => {
  console.log('env.MONGO_URL:', process.env.MONGO_URL);  // Not the URL we set in `npm run env`
});

How do I achieve my goal with npm scripts?

I use a shell script to solve this.

// package.json
{
  "scripts": {
    "start": "./.scripts/prod-meteor.sh",   // run a shell script
    ...
  }
}
# ./.scripts/prod-meteor.sh
export MONGO_URL="mongodb://account:password@host:port/database"
export MAIL_URL="smtp://USERNAME:PASSWORD@HOST:PORT"
meteor run $@   # forward shell parameters to meteor run

Now you can run npm start or npm start ios android for mobile development.

1 Like