1

Greetings I am learning javascript now and I want to know how to implement modularity in it. I googled some but didn't fully understood the method.

So I kindly ask for help. How to make this work?

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test Modularity</title>
  </head>
  <body>
      <button id="buttonFoo" type="button" onclick="foo()">Foo</button>
      <button id="buttonBar" type="button" onclick="bar()">Bar</button>
      <script src="main.js"></script>
  </body>
</html>

main.js

import { foo } from './foo.js'
import { bar } from './bar.js'

foo.js

export function foo()
{
    alert("FOO!");
}

bar.js

export function bar()
{
    alert("BAR!");
}

When I click on the buttons I get this error in debug.

Uncaught ReferenceError: foo is not defined
Uncaught ReferenceError: bar is not defined

Thanks in advance for your time.

1 Answer 1

2

In short, you can't just throw module-using code into the browser and expect it to work, because the web was built before modules existed, and so its "default module system" is to have none at all.

The longer answer is that you need to follow certain steps, detailed here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

Most importantly, you need to use a type of "module" on your script tags:

<script type="module">/* ... your code */ </script>

or:

<script type="module" src="index.js"></script>
Sign up to request clarification or add additional context in comments.

2 Comments

I put the ``` <script type="module" src="./main.js"></script> ``` but I got the ``` Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///path/to/main.js. (Reason: CORS request not http). ``` error it has opened a whole new rabbithole that I don't know how to solve.
From the article I linked: "You need to pay attention to local testing — if you try to load the HTML file locally (i.e. with a file:// URL), you'll run into CORS errors due to JavaScript module security requirements. You need to do your testing through a server." In other words, the root domain of your HTML file and all JS files needs to be the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.