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.
Create React App supports custom environment variables without the need to install any other packages. There are two methods of adding environment variables: Through the shell (temporary, lasts as long as shell session last, and varies depending on the OS type).
Method 1: Using npm scripts to set environment variables Let's add some environment variables with a --env flag in our scripts. We've added the --env. API_URL= part in both scripts. Now, run your npm run dev command, go to your React component and use the process.
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
Resource: https://github.com/topheman/webpack-babel-starter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With