简体   繁体   中英

Environment variables - undefined

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:

在此处输入图片说明

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.

PROBLEM SOLVED:

  1. Uninstall dotenv
  2. Remove these two from main app.js file:
const dotenv = require('dotenv')
dotenv.config();
  1. Remove the flag --env from npm start script.

  2. Remove node: { fs: 'empty' } from webpack.config.js file

  3. Install dotenv-webpack , and follow the instructions from there.

No need for REACT_APP prefix.

Fixed configuration files

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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