简体   繁体   中英

Using dotenv module with React

I have dotenv in my dependencies of my app. Following the directions, I have a .env file and inside is NODE_ENV=development .

In my main.js file, I'm running a simple require('dotenv').config(); and yet when I access process.env , I'd expect an object and I get {}

What am I doing wrong here? Thanks

dotenv only works in the server-side. To use .env in the client side with webpack, use dotenv-webpack .

  1. Install the package, yarn add dotenv-webpack -D OR npm install dotenv-webpack --save
  2. Add it to your Webpack config file.

     // webpack.config.js const Dotenv = require('dotenv-webpack'); module.exports = { ... plugins: [ new Dotenv({ path: './.env', // Path to .env file (this is the default) safe: true // load .env.example (defaults to "false" which does not use dotenv-safe) }) ] ... }; 
  3. Add .env to your .gitignore file

NOTE: Your .env files can include sensitive information. Because of this, dotenv-webpack will only expose environment variables that are explicily referenced in your code to your final bundle.

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