'Module not found: Error: Can't resolve 'fs' in dotenv/lib

All of a sudden, when creating a react production build, I get this error.

> [email protected] build
> react-scripts build

Creating an optimized production build...
Failed to compile.

Module not found: Error: Can't resolve 'fs' in '/workspace/safe-courier/client/node_modules/dotenv/lib'

I have searched on the web, found similar cases but different frameworks of which all were not of help in regards to this issue.

I have tried to uninstall dotenv and reinstall it again but i get the same error. I'm not sure what could be the problem understanding that fs module is part of nodejs and comes bundled with it



Solution 1:[1]

To solve this:

  1. Create the .env file at the root level of you app
  2. Name your variables beginning with REACT_APP_ // that's the key !!
  3. Restart your server with npm start each time you change an env variable
  4. Use your variable with process.env.NAMEOFYOURVARIABLE

No need of dotenv for your React app.

Solution 2:[2]

I solved the same problem;

  1. npm install dotenv-webpack --save-dev
  2. Create .env file under root folder
  3. create env variable as
REACT_APP_YOURVARIABLE=itsvalue
  1. Create webpack.config.js file under the root folder with following content
const Dotenv = require('dotenv-webpack');
module.exports = {
    plugins: [
        new Dotenv()
    ]
}
  1. Then wherever you want to use variable in .env write
process.env.REACT_APP_YOURVARIABLE

There is no need to import dotenv. It is already done in webpack.config.js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nimantha
Solution 2 Tyler2P