简体   繁体   中英

Importing module in JS script inside HTML file

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM