Search code examples
javascriptrequirereferenceerror

Require function is not defined


I am working on a 3D viewer using express.

My problem is that I am trying to require the file system module in one (not the main one) of my JS files. When I try to load the browser, the console gives me the next message:

ReferenceError: require is not defined

My project structure is:

  • node_module
  • src
    • js
      • app.js // the problem is here
    • views
      • index.ejs
  • server.js

Solution

  • A short example of how to use importing with the browser:

    1. Create index.html with next content:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <script type="module" src="./main.js"></script>
    </body>
    </html>
    

    Check script tag - we set type="module" - this instructs the browser that we are using module system

    1. Create main.js script with:
    import name from './name.js';
    
    console.log(name);
    
    1. Create name.js file:
    const name = 'test';
    export default name;
    

    Now you need to run this app. The easiest way is to use WebServer For Chrome

    Start the application and check the console. You should see that the 'test' is logged.

    That's it. Please, keep in mind that this is just an example. We don't touch minification, caching and other important things.