How To Fix Uncaught ReferenceError: require is not defined In Browser Side Javascript Code

I have 2 js files and 1 Html file. I import the 2 js files into the Html file. In the js file, I use the method require() to include other js files or modules. And when I browse the Html file in a web browser, It shows the error message Uncaught ReferenceError: require is not defined. This article will tell you how to fix it.

1. How To Fix Uncaught ReferenceError: require is not defined In The Browser Side Javascript Code.

  1. As we know the web browser ( or client-side javascript engine ) does not support the require() function, then it throws this error Uncaught ReferenceError: require is not defined.
  2. The require() function is only supported in Node.js which runs on the server-side.
  3. If you want to import/export the js module using client-side javascript in the web browser, you should use the ES6 module import/export syntax.
  4. Below js file defines an ES6 module in javascript. The js file name is test.js, so the js module name is also the test.js.
  5. It uses the export keyword to export the function and variable to other js files. At least, one of the exported functions should have the keyword default decorator.
    // Define & export a module function.
    export default function hello(name){
          alert('hello ' + name);
    // Define and export a module property.
    export const moduleName = 'test2';
  6. If you want to import the above js module exported function and variable in other js modules, you can write the below code in a file test1.js. You can use the keyword import to import the test.js module exported function and variable into it and use it.
    // Import the test.js module exported function and variable.
    import hello, { moduleName } from "./test.js";
    // Export another fucntion from this module test1.js.
    export default function helloFromTest1(name){
       // Call the test.js module exported function hello(). 
  7. If you want to include the above js module file in the Html file, you should add the below source code in the Html file source code.
  8. The script tag’s type attribute value must be “module“, otherwise, it will throw errors ( please refer to How To Fix Javascript Uncaught SyntaxError: Unexpected token ‘export’ & Uncaught SyntaxError: Cannot use import statement outside a module ).
    <script type="module" src="./js/test1.js" charset="utf-8"></script>
  9. The above method demonstrates how to export and import ES6 js module exported functions in another js module file, but if you want to use the js module exported function in the global scope javascript source code, you can read the article How To Define ES6 Javascript Module And Call Module Exported Function In Html Code Correctly.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.