Search code examples
javascripthtmles6-modules

How to export a module from an linked JavaScript file


In my project if I load the main.js file the following works:

modules.exports = { property: value }

But if I load in a web page and it links to a script like so:

<!DOCTYPE html>
<html>
  <head>
    <script src="main.js"></script>
  </head>
</html>

Then when I get an error,

ReferenceError: module is not defined 

Solution

  • The module.exports syntax is a feature of CommonJS modules, which is a module system used in Node.js but not supported in web browsers natively.

    To use ES6 modules, you'll need to use a type="module" attribute on your script tag like this:

    <!DOCTYPE html>
    <html>
      <head>
        <script type="module" src="main.js"></script>
      </head>
    </html>