admin管理员组文章数量:1410737
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:
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:
Share edited Dec 4, 2019 at 4:15 Tony 20.2k7 gold badges41 silver badges62 bronze badges asked Dec 3, 2019 at 10:14 user11910832user11910832 7-
try npmjs./package/dotenv to use
.env
variables – Harish Commented Dec 3, 2019 at 10:16 -
Added
dotenv
same result. – user11910832 Commented Dec 3, 2019 at 10:17 -
REACT_APP
prefix is a feature of create-react-app cli, not of react. try this: npmjs./package/dotenv-webpack – Murli Prajapati Commented Dec 3, 2019 at 10:33 -
1
@grecdev A very good article in setting up
.env
file for react server-side as well as for client-side app. medium./@trekinbami/… – Darpan Rangari Commented Dec 3, 2019 at 10:35 - @grecdev Also I can see you are not using any parameter after --env in your start script this might override all the variable defined in .env file, either use --env in the script or use .env file. – Darpan Rangari Commented Dec 3, 2019 at 10:41
4 Answers
Reset to default 2PROBLEM SOLVED:
- Uninstall
dotenv
- Remove these two from main
app.js
file:
const dotenv = require('dotenv')
dotenv.config();
Remove the flag
--env
fromnpm start
script.Remove
node: { fs: 'empty' }
fromwebpack.config.js
fileInstall dotenv-webpack, and follow the instructions from there.
No need for REACT_APP
prefix.
Fixed configuration files
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.
try https://www.npmjs./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.
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
本文标签: javascriptEnvironment variablesundefinedStack Overflow
版权声明:本文标题:javascript - Environment variables - undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744952426a2634156.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论