[英]Environment variables - undefined
I want to use environment variables
.我想使用
environment variables
。 I made a custom react app environment
.我做了一个自定义的
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
.但是
.env
文件中的变量给出了undefined
,而process.env
给出了一个empty object
。
I added dotenv and REACT_APP
prefix to the variable.我在变量中添加了dotenv和
REACT_APP
前缀。
And in webpack.config.js
file i added node: { fs: 'empty' }
, from here在
webpack.config.js
文件中,我添加了node: { fs: 'empty' }
,从这里开始
Here are my configurations .这是我的配置。
Folder structure:文件夹结构:
You have to put REACT_APP
in front of the variable name you want to have你必须把
REACT_APP
放在你想要的变量名前面
eg:/例如:/
REACT_APP_YOUR_VAR="something"
You don't need to install Dotenv or something else, because React has its own.你不需要安装 Dotenv 或其他东西,因为 React 有它自己的。
PROBLEM SOLVED:问题解决了:
dotenv
dotenv
app.js
file:app.js
文件中删除这两个:const dotenv = require('dotenv')
dotenv.config();
Remove the flag --env
from npm start
script.从
npm start
脚本中删除标志--env
。
Remove node: { fs: 'empty' }
from webpack.config.js
file从
webpack.config.js
文件中删除node: { fs: 'empty' }
Install dotenv-webpack , and follow the instructions from there.安装dotenv-webpack ,然后按照那里的说明进行操作。
No need for REACT_APP
prefix.不需要
REACT_APP
前缀。
Fixed configuration files固定配置文件
try https://www.npmjs.com/package/dotenv to use .env
variables尝试https://www.npmjs.com/package/dotenv使用
.env
变量
In your entry JS file add below code snippet (maybe your ./src/assets/js/app.js
)在您的条目 JS 文件中添加以下代码片段(可能是您的
./src/assets/js/app.js
)
const dotenv = require('dotenv')
dotenv.config()
and restart your app.并重新启动您的应用程序。
You can use webpack.DefinePlugin您可以使用 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然后在您的代码中只需使用 process.env.NODE_ENV 来访问 ENV 变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.