【问题标题】:Importing module in JS script inside HTML file在 HTML 文件中的 JS 脚本中导入模块
【发布时间】:2021-11-18 11:14:42
【问题描述】:

为什么第 3 行打破了这个例子?注释掉第 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>

在 MS Edge 93 中测试。

【问题讨论】:

  • 你得到什么错误?
  • 我在浏览器中测试时没有任何反馈
  • 你打开了控制台?
  • 哦,我不敢相信我不知道在控制台上看到错误,谢谢!

标签: javascript html import


【解决方案1】:

首先,"script.js" 应该是 "./script.js"。之后,控制台显示错误

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.

解决方法是使用this question 中的服务器。

【讨论】:

  • script.js and ./script.js`没有区别
  • 你会这么认为,但是"script.js" 给了我一个“找不到文件”的错误。
  • 他是对的,使用或省略./ 无关紧要。
【解决方案2】:

它会破坏您的代码,因为 script.js 不存在。为了能够导入模块,您必须在使用前添加它

【讨论】:

  • 你怎么知道文件不存在?
猜你喜欢
  • 1970-01-01
  • 2020-06-11
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多