Home > Net >  Module not found: Error: Can't resolve 'fs' in '/home/bassam/throwaway/chakra-ts
Module not found: Error: Can't resolve 'fs' in '/home/bassam/throwaway/chakra-ts

Time:07-15

Created app via yarn create react-app chakra-ts --template @chakra-ui/typescript.

Added dotenv via yarn add dotenv

Added the following to App.tsx according to dotenv docs:

import * as dotenv from 'dotenv';

dotenv.config();

Now when I do yarn build it fails with the following:

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

Module not found: Error: Can't resolve 'fs' in '/home/bassam/throwaway/chakra-ts/node_modules/dotenv/lib'


error Command failed with exit code 1.

Here's my package.json:

{
  "name": "chakra-ts",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@chakra-ui/react": "^2.2.4",
    "@emotion/react": "^11.0.0",
    "@emotion/styled": "^11.0.0",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.0.1",
    "@testing-library/user-event": "^14.1.0",
    "@types/jest": "^25.0.0",
    "@types/node": "^12.0.0",
    "@types/react": "^18.0.9",
    "@types/react-dom": "^18.0.4",
    "framer-motion": "^6.2.9",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-icons": "^3.0.0",
    "react-scripts": "5.0.1",
    "typescript": "^4.6.3",
    "web-vitals": "^0.2.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Am I doing something wrong here?

Backstory: I was trying to upgrade another react app to react 18, but I kept getting this same error (the app builds error free in react 17). I wanted to reproduce the problem in a simpler app, and here it is.

CodePudding user response:

TL;DR Since you created your project with create-react-app, you should add environment variables the way the docs suggest.

The reason you are running into this error is because dotenv is meant to be used in Node.js, not in the browser. If you want to use dotenv in a frontend application, you need to configure your bundler (e.g. Webpack) to transform the environment variables at build time. For example, take a look at this Webpack plugin for dotenv.

Since you are using create-react-app which hides the webpack config from you, you must either eject and configure webpack yourself (not recommended) or use their recommended way of using environment variables (which is to prefix environment variables with REACT_APP_ without adding the dotenv dependency).

  • Related