Fix "require is not defined" in JavaScript/Node

A common error you'll run into, especially when transitioning from writing JavaScript in the Node runtime to writing JavaScript in the browser, is "Uncaught ReferenceError: require is not defined". The two environments have different ways of importing modules, so trying to import code in the browser like you would in Node results in this error.

However, this isn't the only time you might run into this error. Here are the various ways you might run into it:

  • You try to use the require statement in the browser
  • You try to use require in Node when ES modules are specified in package.json via "type": "module"
  • You're trying to use require in a file ending in .mjs, which typically specifies ES modules

Node

If you encounter this error in a Node environment, you've likely either specified to use ES modules via package.json or via the command line.

In case it is specified in package.json, you can fix this by removing the following line in the file:

{
 "type": "module"
}
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

If you specified to use ES modules via the command line with --eval, you can fix this by removing the --input-type parameter from the command line call.

Browser

The require method is not available in the browser. To solve this, you have a few options, a few of which we'll briefly describe here.

You can use a bundler like Webpack, which compiles your JavaScript code into a format that is compatible with the browser. Internally, a bundler like this would remove the require statement and instead merge the code into a single file. In some cases, some bundlers may even convert your require calls to import since that is supported by most browsers.

Another option is to just use ES modules, which is natively supported by most browsers. In order to use this, you'll need to convert all of your require statements to import statements. You'll also need to explicitly specify the type of the module in the <script> tag, like this:

<script type="module" src="./app.js"></script>

How you choose to fix this may depend on personal preference, if you're using a bundler, etc.

Last Updated: April 12th, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms