brysgo / babel-plugin-inline-dotenv

Load your .env file and replace 'process.env.MY_VARIABLE' with the value you set.
124 stars 13 forks source link

Switch between two .env files - for prod and dev #38

Open superKalo opened 5 years ago

superKalo commented 5 years ago

Hi. I've integrated this plugin on my Expo (React Native) project following these steps.

Can you please tell me if it is possible to configure the plugin to use the .env file for development and another file, .env.production, for production?

Gregoirevda commented 5 years ago

cp .env.{staging} .env

aiham commented 5 years ago

@superKalo In my babel.config.js file I have this:

const fs = require('fs');
const path = require('path');

module.exports = function(api) {
  api.cache(true);

  const envName = process.env.MY_ENV_NAME || 'local';
  const dotEnvPath = path.resolve(__dirname, 'config', `${envName}.env`);
  if (!fs.existsSync(dotEnvPath)) {
    throw new Error(
      `Babel config couldn't find dot env file path: ${dotEnvPath}`,
    );
  }
  console.info(`Loading environment variables from: ${dotEnvPath}`);

  return {
    presets: ['babel-preset-expo'],
    plugins: [['inline-dotenv', { path: dotEnvPath }]],
  };
};

and in package.json I have:

  "scripts": {
    "start": "expo start",
    "start:prod": "MY_ENV_NAME=prod yarn start",
    "start:staging": "MY_ENV_NAME=staging yarn start"
  }

Sometimes the babel config gets cached so you'll need to add --clear to the start command.