'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:
- Create the .env file at the root level of you app
- Name your variables beginning with REACT_APP_ // that's the key !!
- Restart your server with npm start each time you change an env variable
- Use your variable with process.env.NAMEOFYOURVARIABLE
No need of dotenv for your React app.
Solution 2:[2]
I solved the same problem;
npm install dotenv-webpack --save-dev
- Create
.env
file under root folder - create
env
variable as
REACT_APP_YOURVARIABLE=itsvalue
- Create webpack.config.js file under the root folder with following content
const Dotenv = require('dotenv-webpack');
module.exports = {
plugins: [
new Dotenv()
]
}
- 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 |