How to Solve Uncaught ReferenceError: required is not defined

To solve Uncaught ReferenceError: required is not defined in JavaScript, download the requireJS from its official website, put it on your script folder, and then include it via script tag on your HTML file.

<!DOCTYPE html>
<html>

<head>
  <title>RequireJS on Browser</title>
  <script data-main="scripts/main" src="scripts/require.js"></script>
</head>

<body>
  <h1 id="header">This is body</h1>
</body>

</html>

Here the data-main attribute is used by RequireJS to load a specified js file inside the data-main attribute just after the require.js file is loaded. Here in the above example, main.js is loaded after require.js.

Your project structure should be as:

→index.html

→scripts

       →main.js 

       →lodash.js

       →require.js

Uncaught ReferenceError: required is not defined

The uncaught ReferenceError: required is not defined in JavaScript error usually occurs when JavaScript doesn’t know how to handle the require() function. The require() function is not supported by browsers by default.

The require() function is available on NodeJS only but if you want it to be used on the browser you have to add the require() function on the browser by using the ReactJS library.

Uncaught ReferenceError in Node.js

To solve uncaught ReferenceError in Node.js:

  1. Change the module type in package.json form module to commonjs: “type”:”commonjs”.
  2. You can delete the whole “type”:”module” string from package.json.
  3. You can change require to import.
    // const express = require('express');
    
       import express from 'express';

    Conclusion

    Sometimes, you might face some unwanted errors while using JavaScript. Similarly, there is an error you may come across known as Uncaught ReferenceError: require is not defined. So in this article, we showed how to fix this error in JavaScript.

    That’s it for this tutorial.

    See also

    How to solve reference error: window is not defined

    How to solve reference error: document is not defined

    How to Use a Debugger in JavaScript

    1 thought on “How to Solve Uncaught ReferenceError: required is not defined”

    1. I am coding in electron.js a small application, which has several windows for different HTML, which must communicate with each other. I need to code in each HTML, the following instruction, wrapped in a “script” tag:

      const { ipcRenderer } = require(‘electron’)

      ..and I get the error: “Uncaught ReferenceError: require is not defined”.

      The require() instructions inside the main program (index.js), work fine. It only fails in the given situation.

      I would be very grateful for your help, since I have searched all the documentation that exists and I have not been able to solve the problem or progress with the application.

      Reply

    Leave a Comment