Home > front end >  Importing module in JS script inside HTML file
Importing module in JS script inside HTML file

Time:09-26

Why does line 3 break this example? It works fine with line 3 commented out.

<button id="button">Click me</button>
<script type="module">
  import { foo } from "script.js";    // BREAKS THINGS

  document.getElementById("button")
    .addEventListener("click",
      function(){ alert("hello") } );
</script>

Tested in MS Edge 93.

CodePudding user response:

Well firstly, "script.js" should be "./script.js". After that, the console shows an error

Access to script at 'file:///C:/Users/jordanb/Dropbox/Git/test/script.js' from
origin 'null' has been blocked by CORS policy: Cross origin requests are only
supported for protocol schemes: http, data, chrome-extension, edge, https,
chrome-untrusted.

The fix is to use a server as in this question.

CodePudding user response:

It breaks your code, since script.js doesn't exist. In order to be able to import the module you have to add it before using

  • Related