Reputation: 620
I want to store variable in .env variable and use it like process.env
I added .env file in root directory
REACT_APP_FOO = abcc111
webpack.config.dev.js
plugins: [
new webpack.ProvidePlugin({
React: 'react'
}),
new webpack.DefinePlugin({
"process.env":{
'REACT_APP_FOO': JSON.stringify(process.env.REACT_APP_FOO)
}
})
],
App.js
console.log(process.env);
Result is:
{REACT_APP_FOO: undefined}
Please let me know if i am missing anything here.
Upvotes: 0
Views: 1076
Reputation: 11257
Steps to add .env
contents
1) npm install dotenv --save
2) At top of webpack config file
const dotenv = require('dotenv').config({path: __dirname + '/.env'});
3) Then create a .env file at the root directory of your application and add the variables to it.
//contents of .env
REACT_APP_FOO = abcc111
4) webpack config file
new webpack.DefinePlugin({
"process.env": dotenv.parsed
}),
4) Add .env
to your .gitignore
file so that Git ignores it and it never ends up on GitHub. Need to restart application after adding variable in .env file.
If you are using create-react-app, it uses react-scripts
which has dependency of dotenv
so you don't have to install and configure, you could just create .env
file and use in your application.
Convention being name should start with REACT_APP
Hope that helps!!!
Upvotes: 1