Blog |

How to Fix ReferenceError: Require is Not Defined in JavaScript

How to Fix ReferenceError: Require is Not Defined in JavaScript
Table of Contents

The ReferenceError: require is not defined error occurs if the JavaScript require method is used but is not available in the current context.

What Causes Javascript ReferenceError: Require is Not Defined

In JavaScript, require is a method used to load modules or external dependencies in a Node.js environment. However, it is not a built-in feature of standard JavaScript and is not recognized by web browsers.

The ReferenceError: require is not defined error usually occurs when using require in the following scenarios:

  • A web browser environment: Since require is not a standard feature of web browsers, it will not work if it is used in a script intended to be executed in a browser.
  • A non-Node.js environment: Since require is specific to Node.js, if JavaScript code is executed outside of a Node.js environment, require will not be recognized.

ReferenceError: Require is Not Defined Example

Here’s an example of a Javascript ReferenceError: require is not defined thrown trying to use the require function:

const fs = require('fs');

In the above example, the fs module is attempted to be imported in a web browser environment by calling the require function. However, since require is not available in web browsers, running the above code throws a ReferenceError:

Uncaught ReferenceError: require is not defined

How to Fix ReferenceError: Require is Not Defined

The Javascript ReferenceError: require is not defined error can be fixed by using the following approaches:

  • If the error occurs in a web browser environment, a different method to load external dependencies should be considered. For example, <script> tags or a module loader like RequireJS.
  • In a non-Node.js environment, external dependencies should be loaded using a method compatible with the environment.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Try it today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape