简体   繁体   English

环境变量 - 未定义

[英]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.我在变量中添加了dotenvREACT_APP前缀。

And in webpack.config.js file i added node: { fs: 'empty' } , from herewebpack.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:问题解决了:

  1. Uninstall dotenv卸载dotenv
  2. Remove these two from main app.js file:从主app.js文件中删除这两个:
const dotenv = require('dotenv')
dotenv.config();
  1. Remove the flag --env from npm start script.npm start脚本中删除标志--env

  2. Remove node: { fs: 'empty' } from webpack.config.js filewebpack.config.js文件中删除node: { fs: 'empty' }

  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM