How to Fix Uncaught ReferenceError: required is not defined

To fix the Uncaught ReferenceError: required is not defined in JavaScript, “download the requireJS” from its official website, put it in your script folder, and 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 followed as:

→index.html

→scripts

       →main.js 

       →lodash.js

       →require.js

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 brow,ser you have to add the require() function by using the ReactJS library.

Uncaught ReferenceError in Node.js

To fix the uncaught ReferenceError in Node.js:

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

    That’s it.

    1 thought on “How to Fix 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