Skip to content

Instantly share code, notes, and snippets.

@joelbowen
Last active September 19, 2018 13:49
Show Gist options
  • Save joelbowen/1d2f2dfa471efad2154e6318c195b77e to your computer and use it in GitHub Desktop.
Save joelbowen/1d2f2dfa471efad2154e6318c195b77e to your computer and use it in GitHub Desktop.
create-react-native-app environment variables

Change your app.json to base-app.json and untrack the original file in your .gitignore

Then add something like "generateConfig": "rimraf app.json && node generateConfig" to your package.json scripts, and yarn generateConfig && react-native-scripts start to scripts like "start" or any others that may need app.json generated.

const baseConfig = require('./base-app.json');
console.log('Application configuration loaded from base-app.json');
const config = Object.assign({}, baseConfig);
const fs = require('fs');
const path = require('path');
// Create an array of env files
const dotEnvFiles = [path.join(__dirname, '.env'),];
console.log('Environment configuration settings loaded from', dotEnvFiles);
// Load env files, supress warnings
dotEnvFiles.forEach(dotEnvFile => {
if (fs.existsSync(dotEnvFile)) {
// eslint-disable-next-line
require('dotenv').config({
path: dotEnvFile,
});
}
});
// We will only use REACT_NATIVE_APP_* environment variables
const REACT_NATIVE_APP = /^REACT_NATIVE_APP_/i;
console.log('Using environment configurations that match', REACT_NATIVE_APP);
const getClientEnvironment = () => {
const env = {};
Object.keys(process.env)
.filter(key => REACT_NATIVE_APP.test(key))
.forEach(key => {
env[key] = process.env[key];
});
return env;
};
config.expo.extra = getClientEnvironment();
console.log('Configuration contents generated, writing to app.json');
fs.writeFileSync('app.json', JSON.stringify(config, null, 2), 'utf8');
@andrewsantarin
Copy link

andrewsantarin commented Aug 13, 2018

@joelbowen liking it so far!

Mine here: https://gist.github.com/andrewsantarin/699da98a6082d8f413a5e060092f35f6, which itself is a heavily modified react-scripts/config/env.js adapted with your code.

However, I'm at a loss as to how I can allow things like .env.${NODE_ENV}.${isLocal ? 'local' : ''} because the NODE_ENV seems to only be assigned until after Expo has loaded, which is responsible for setting the app env.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment