Reputation:
I want to use environment variables
. I made a custom react app environment
.
Everything is ok, the app runs properly, no errors. But the variables from .env
file gives undefined
and the process.env
gives an empty object
.
I added dotenv and REACT_APP
prefix to the variable.
And in webpack.config.js
file i added node: { fs: 'empty' }
, from here
Here are my configurations.
Folder structure:
Upvotes: 4
Views: 5008
Reputation:
PROBLEM SOLVED:
dotenv
app.js
file:const dotenv = require('dotenv')
dotenv.config();
Remove the flag --env
from npm start
script.
Remove node: { fs: 'empty' }
from webpack.config.js
file
Install dotenv-webpack, and follow the instructions from there.
No need for REACT_APP
prefix.
Fixed configuration files
Upvotes: 2
Reputation: 20092
You can use webpack.DefinePlugin
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
],
Then in your code simply use process.env.NODE_ENV to access ENV variable
Upvotes: 0
Reputation: 394
You have to put REACT_APP
in front of the variable name you want to have
eg:/
REACT_APP_YOUR_VAR="something"
You don't need to install Dotenv or something else, because React has its own.
Upvotes: 1
Reputation: 1911
try https://www.npmjs.com/package/dotenv to use .env
variables
In your entry JS file add below code snippet (maybe your ./src/assets/js/app.js
)
const dotenv = require('dotenv')
dotenv.config()
and restart your app.
Upvotes: 0