Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Require Not Defined in React App — Why?

Getting ‘require is not defined’ in your browser-based React app? Discover why Babel and ES modules might be the cause.
Frustrated React developer looking at require is not defined error in frontend code, CommonJS vs ESModules battle in the background, red console warning Frustrated React developer looking at require is not defined error in frontend code, CommonJS vs ESModules battle in the background, red console warning
  • ⚠️ 'require is not defined' occurs because Node.js’s CommonJS system doesn’t run in browsers.
  • ⚙️ Babel doesn’t polyfill require() — it only transforms syntax, not runtime environments.
  • 🧩 Vite and Webpack must be correctly configured to bridge ESM and CJS compatibility.
  • 🔁 Dynamic import() is the recommended modern approach for lazy loading in React.
  • 📦 Always prefer ESM-compatible libraries to avoid runtime errors in the browser.

Are you seeing the require is not defined error in your React app? Many people run into this. This error can confuse new and experienced JavaScript developers, especially when building for the browser with modern tools like Babel and ES modules. We will explain the problem and show you how to fix it.


Understanding require is not defined

If you see the require is not defined error in your React app running in the browser, the problem is simple. You are using something that is not in the environment where the code runs. The require() function is part of Node.js's module system, called CommonJS. This system is not available in browsers.

By default, React runs in the browser. So, when the browser sees a line like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const lodash = require('lodash');

…it throws a reference error. This happens because the browser's JavaScript runtime, ECMAScript, does not define require. Now, JavaScript in the browser uses ECMAScript Modules (ESM). These modules use the import and export syntax.

So, if require() is used and not changed for the browser, your code will fail when it runs there.


ES Modules vs CommonJS

To really understand this error, you need to know how JavaScript handles modules. Before ECMAScript Modules were standard, Node.js developers mainly used CommonJS. Many packages still use it today.

Let's look at both module systems.

ES Modules (ESM)

ES Modules are the modern JavaScript module system. Browsers have supported them since about 2017. They are part of the ECMAScript standard. They offer a simple, efficient way to organize and reuse code.

Main features:

  • They use import and export.
  • They allow tree-shaking (removing unused code).
  • Their structure is static, so tools can check it when building.
  • Modern browsers support them directly.
  • They work with React's tools and bundlers like Webpack or Vite.

Example:

import fs from 'fs';
export const greet = () => console.log('Hello world!');

CommonJS (CJS)

CommonJS was made before ESMs became standard. Node.js used CJS as its main module system for many years. Because of this, many older packages and backend code still use it.

Main features:

  • They use require() and module.exports.
  • They load code when needed, so tools cannot check them when building.
  • Browsers do not support them directly.
  • They were made for Node.js and are for server-side code.

Example:

const fs = require('fs');
module.exports = { greet: () => console.log('Hello world!') };

📊 MDN says that browser support for ES modules only became widespread after 2017. This means many third-party modules still use CommonJS for exports.


Common Places You Might Be Using require() Without Realizing

It's not always clear that you have a require() call in your own code. This problem often comes from other places, such as dependencies or code you copy and paste.

Here are common ways require() might be used by mistake:

  • 🧩 Third-party packages: Especially older libraries not changed for ESM.
  • 📚 Online tutorials and GitHub code: These often show CommonJS syntax for Node.
  • 🏗️ Old React projects or frontends: Many of these began when require() was common.
  • 🔁 Shared code for server and client: Code made to run on both the server and client might accidentally bring in Node-only modules like fs or path.
  • 🧪 Automatic code changes: Tools like Webpack loaders or transpilers might add CJS plugins without you knowing.

If any of these get to the client side, you will see the "require is not defined" error when your React app starts in the browser.


How Babel Fits In

Babel is a JavaScript compiler. It changes modern JS (and JSX) into code that can run in older systems. But Babel does not change how modules run. It only changes how they are written.

Main Babel Ideas:

  • Syntax Changes: Babel changes import/export to use a format that works with the environment.
  • No Runtime Code: Babel does not define require(). If require() is used, Babel does not add support for it.
  • Plugins Needed for Module Changes: Standard Babel settings might not change CommonJS to ES modules or the other way around.

Here is what Babel processing does and does not do:

Task Babel Can Do It?
Change ES6+ to ES5 ✅ Yes
Change JSX -> JS ✅ Yes
Add require() fallback ❌ No
Change CommonJS to ESM ✅ With plugin

Helpful Plugins for Module Work:

  • @babel/preset-env: Makes modern JS syntax work in older environments.
  • @babel/plugin-transform-modules-commonjs: Changes ES module syntax into CommonJS if you are making code for Node.js.
  • babel-plugin-transform-remove-require: Removes require() statements if needed for the browser.

But remember, Babel by itself does not manage dependencies or put code together. That is the bundler’s job.


Are Your Bundler Settings Helping or Hurting?

Your bundler (like Webpack, Vite, Parcel) changes and puts your code together into one or more files for the browser. Handling module types is a big part of this.

Webpack Advice:

Webpack is pretty flexible. It understands both CommonJS and ESM with the right settings. But when you are making code for the browser, you must:

  • Turn off Node.js modules that do not work on the web.
  • Set correct fallbacks or aliases, especially for packages like fs, path, crypto.
resolve: {
  fallback: {
    fs: false,
    path: require.resolve('path-browserify'),
    crypto: require.resolve('crypto-browserify')
  }
}

Webpack 5 no longer automatically adds support for Node.js modules. You must do this by hand if truly needed.

Things to Know About Vite:

Vite is ESM-first. It does not allow CommonJS without extra settings. Vite is fast and easy for beginners, and it makes you use modern coding methods.

  • Use vite-plugin-commonjs or vite-plugin-polyfill-node if you need older compatibility.
  • Check that your dependencies support ESM only.
  • Be careful with server-side modules (like os, fs, crypto). They should not be in a Vite project.

Fixing require is not defined — How to Do It

✅ Replace require() with import:

The best way is to make all your code use ESM.

Before:

const axios = require('axios');

After:

import axios from 'axios';

✅ Use import() for conditional loading:

Using import() lets libraries load only when needed:

const loadLibrary = async () => {
  const lib = await import('some-lib');
  lib.doSomething();
};

This works well for components that load later. It also helps split code better in frameworks like React.

✅ Ensure All Imported Libraries Are ESM-Compatible

Check if you are using a recent version of a library:

  • Look in the package.json file. Does it show a module field?
  • Think about changing packages if there is no ESM version.
  • Use tools like bundlephobia to check its size and how well it works when building.

Check if a Dependency Still Uses CommonJS

Here is how to check your dependencies for problems:

🔍 How to check:

  1. Look at the package.json file of the library:

    • "main" means CJS.
    • "module" means ESM.
  2. Check the file names:

    • .cjs → CommonJS
    • .mjs → ES modules
  3. Use this command:

    npm pkg get module
    
  4. See if the package bundler creates different builds:

    • Look for entries like "exports": { "import": ..., "require": ... }

If modules are CJS-only, use Babel plugins or a bundler fix to make them work in the browser.


Why You Should Avoid require() in Frontend React Apps

Using require() in React frontend apps often leads to confusion. It does not work with modern standards.

Here’s why it is best to avoid it:

  • React apps use ESM by default.
  • Dynamic import works better for splitting code and React.lazy.
  • It makes bundling simpler and works better.

Use React.lazy with dynamic import:

const SomeComponent = React.lazy(() => import('./SomeComponent'));

This loads components only when needed. And it fits with how React can render things at the same time.


Migrating CommonJS or Legacy Code Without Breaking Things

Older code often uses require() a lot. Changing it needs specific steps and patience.

Helpful Tips for Changing Code:

  • Use Babel plugins like babel-plugin-transform-modules-commonjs.
  • Change one module at a time.
  • Add integration tests to make sure nothing breaks.
  • Mark server-only files clearly so they are not accidentally brought into the frontend.

Tools like jest-transform-stub can create fake incompatible imports for tests.


Server-Side Rendering Scenarios (Next.js, etc.)

Server-side rendering (SSR) tools like Next.js make module handling a bit harder.

Things to Know for SSR:

  • On the server, you can use require(). This is because it runs in Node.js.
  • On the client, using require() will give you the "require is not defined" error.

Do not write code that can mean two things and runs in both places. When bringing in code on the browser side, use:

if (typeof window !== 'undefined') {
  import('some-client-only-package').then((lib) => lib.doStuff());
}

Or use Next.js’s method for imports:

import dynamic from 'next/dynamic';

const Component = dynamic(() => import('some-library'), { ssr: false });

Be careful with ssr: false. It turns off server-side rendering. And it can hurt how well your site ranks on search engines if used too much.


Best Practices for Module Compatibility

Follow these tips to keep your frontend code strong, organized, and without errors:

  • Use import/export instead of require/module.exports.
  • Use packages that work with ESM if you can.
  • Do not bring in Node.js tools in frontend code.
  • Set up ESLint to find require() in client-side files.
  • Make sure Babel and Webpack/Vite are set up right for what you need.

Building React Apps That Just Work

You do not want to stop every time a problem between ES modules and CommonJS stops your work. Stop future problems by:

  • Using ESM as the standard.
  • Making linting part of your CI/CD process.
  • Choosing external dependencies carefully.
  • Using dynamic import for loading parts as needed.
  • Reading package docs before you install them!

With the right tools, the same way of writing code, and knowing about the runtime environments, your React app will not show confusing errors like require is not defined.


🎯 Quick Ways to Fix It

🔧 Replace All require():

- const axios = require('axios');
+ import axios from 'axios';

🧹 Babel Plugin to Remove require:

npm install --save-dev babel-plugin-transform-remove-require

And then add it to .babelrc:

{
  "plugins": ["transform-remove-require"]
}

🌐 Fix Node.js modules in Webpack:

resolve: {
  fallback: {
    fs: false,
    path: require.resolve('path-browserify'),
  }
}

🔍 Find problem packages:

npm ls require

This will help you find packages in your dependency list that use require(). It gives you clear ways to fix or change them.


Seeing "require is not defined" can feel like you are debugging with no light. But now you know why it happens. And you understand how tools like Babel, Webpack, and ES modules work together. So you can fix it well. You have the information, so go fix that import.

Found a specific, unusual problem? Tell us in Devsolus's community or docs. Your experience might save another developer a lot of time.


Citations

  • Mozilla Developer Network. (2023). JavaScript modules. Retrieved from MDN
  • Node.js Documentation. (2023). ES Modules vs CommonJS. Retrieved from Node.js
  • Google Chrome DevTools Blog. (2022). Understanding Modules in the DevTools Console.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading