How can I use environment variables defined in .bash_profile in a React application? I have two React apps in production (they're the same project, so they have the same code), but they need to request to different API hosts, and I figured env variables could do the trick.
2 Answers
Use webpack.DefinePlugin. Say you exported FOO and BAR in your .bash_profile, then your webpackconfig should look like:
const config = {
entry: 'somescript',
// ...
module: {
// ...
},
// ...
plugins: [
// ... your plugins
new webpack.DefinePlugin({
'process.env':{
'FOO': process.env.FOO,
'BAR': process.env.BAR
}
})
],
// ...
}
You will be able to access those in your js at compile time via process.env.FOO & process.env.BAR
4 Comments
JSON.stringify(process.env.FOO) otherwise it will not work. Btw, I come from the future.Store the environment variables in the index.html!
if you treat the index.html like a deployment manifest that contains environment-specific values, you can use the same versioned assets (js, css) in every environment!
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="https://assets.myapp.com/favicon.ico">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="https://assets.myapp.com/manifest.json">
<title>React App</title>
<script>
env = {
// Add your environment variables here
api: "https://staging-api.myapp.com"
};
</script>
<link href="https://assets.myapp.com/static/css/main.6bd13355.chunk.css" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<script src="https://assets.myapp.com/static/js/1.a700ff87.chunk.js"></script>
<script src="https://assets.myapp.com/static/js/main.3ec5cdc6.chunk.js"></script>
</body>
</html>
In your code reference the values directly: myApi = window.env.api;
Read more documentation for this methodology at https://immutablewebapps.org
process.env.API_HOST