0

I want to store variable in .env variable and use it like process.env

I added .env file in root directory

REACT_APP_FOO = abcc111

webpack.config.dev.js

plugins: [
    new webpack.ProvidePlugin({
        React: 'react'
    }),
     new webpack.DefinePlugin({
       "process.env":{
       'REACT_APP_FOO': JSON.stringify(process.env.REACT_APP_FOO)
     }
   })
],

App.js

console.log(process.env);

Result is:

{REACT_APP_FOO: undefined}

Please let me know if i am missing anything here.

2
  • In .env try REACT_APP_FOO=abcc111 (remove whitespace before and after equal sign) Commented May 2, 2019 at 7:49
  • @henrik123 still getting same result {REACT_APP_FOO: undefined} Commented May 2, 2019 at 7:51

1 Answer 1

1

Steps to add .env contents

1) npm install dotenv --save

2) At top of webpack config file

const dotenv = require('dotenv').config({path: __dirname + '/.env'});

3) Then create a .env file at the root directory of your application and add the variables to it.

//contents of .env

REACT_APP_FOO = abcc111

4) webpack config file

new webpack.DefinePlugin({
            "process.env": dotenv.parsed
        }),

4) Add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub. Need to restart application after adding variable in .env file.

If you are using create-react-app, it uses react-scripts which has dependency of dotenv so you don't have to install and configure, you could just create .env file and use in your application. Convention being name should start with REACT_APP

Hope that helps!!!

Sign up to request clarification or add additional context in comments.

3 Comments

Is there any way to do this without using any external library? @tarzen
whenever i install this library . i get issues with other library
You need this library to get variables from .env file and add them to process.env. This library has zero dependency and is internally used by create-react-app also. It shouldn't be conflicting with other library. What is the error you are getting. If you can't install this library then just set environment variables in webpack cli like webpack --env.REACT_APP_FOO= abcc111 --config webpack.config.js

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.