简体   繁体   English

在 HTML 文件中的 JS 脚本中导入模块

[英]Importing module in JS script inside HTML file

Why does line 3 break this example?为什么第 3 行打破了这个例子? It works fine with line 3 commented out.它在第 3 行被注释掉的情况下工作正常。

<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.在 MS Edge 93 中测试。

Well firstly, "script.js" should be "./script.js" .那么首先, "script.js"应该是"./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.它会破坏您的代码,因为script.js不存在。 In order to be able to import the module you have to add it before using为了能够导入模块,您必须在使用之前添加它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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