Module Not Found: Error: Can't Resolve 'Fs' in Node_Modules\Dotenv\Lib'

Module Not Found: Error: Can't Resolve 'Fs' in Node_Modules\Dotenv\Lib'

I'm trying to use dotenv with an angle, but when it comes to requiring dotenv

 require('dotenv').config()  
 or
 const Dotenv = require('dotenv-webpack');

I get the following error:

ERROR in ./node_modules/dotenv/lib/main.js Module not found: Error: Can't resolve 'fs' in 'C:\Users\57322\Favorites\Proyecto\core4edu\node_modules\dotenv\lib'

package.json

"dotenv": "^8.2.0",
"dotenv-webpack": "^1.7.0",
2

6 Answers

I think the problem is related to webpack, I had the same problem on a next.js project and here is how I did to fix the problem.

I created a next.conf.js file in my root folder where there is my .env file, I imported dotenv and I exported the module where there is all my environment and these variables as if below.

Finally in my index file and my components I don’t need to import dotenv, I just need to paste my process.env.API_URL.

I hope this example solves your problem.

5

I had a similar situation - working in the webpack development mode, installing dotenv, getting an error "Module not found: Error: Can't resolve 'fs' in node_modules\dotenv\lib'".

I uninstalled dotenv and stayed just with dotenv-webpack for development. I configured the webpack.config.js as it is written in docs.

Everything works now. Env variables are accessible globally without creating any additional file.

if you encounter this error with a create-react-app app, you need to go to the 'react-scripts' webpack config.

node_modules/react_scripts/config/webpack.config.js

under 'resolve':

resolve: {
  ....
  // add the fallback setting below 
  fallback: {
    "fs": false,
    "os": false,
    "path": false
  },
  ....
}

I faced a similar problem. dotenv-webpack installation will suffice. It is the dotenv require statement which is causing problem. Remove that and you will be good to go!

I want to also add TypeScript code on top of @Sidouxie's solution:

  1. Create a file that ends with .d.ts in your root directory.

  2. Add this to the file:

    declare global {
     namespace NodeJS {
       interface ProcessEnv {
         API_URL:string;
       }
      }
    }
    

This will globally check your environment variables in your TypeScript project.

This little addition to package.json starting from Angular 9 (confirmed on Angular 10) fixes this problem.

...
"browser": {
  "fs": false
},
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.