由于错误,Javascript 导入模块到 index.html 未运行

1 javascript ecmascript-6

我正在尝试将模块导入到我的index.html 文件中。

这是代码:

// Index.html:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title></title>

</head>

<body>

<div></div>

  <script type="module" src="module.js"></script>
  <script type="text/javascript">

    import { addTextToBody } from 'module.js';

    addTextToBody('some text here');

  </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

还有js:

export function addTextToBody(text) {

  const div = document.createElement('div');
  div.textContent = text;
  document.body.appendChild(div);

}
Run Code Online (Sandbox Code Playgroud)

我收到这些错误:

未捕获的语法错误:意外的标记 { - 第 18 行

从源“null”访问“module.js”处的脚本已被 CORS 策略阻止:响应无效。因此,不允许访问来源“null”。

我怎样才能解决这个问题?

asy*_*nts 6

  1. module.js应该./module.js
  2. 您不需要在页面开头导入模块(但可以)。
  3. 使用import要求脚本的类型module不仅仅是导入的脚本。
  4. 您应该将模块导入放入<head>(在一开始)。

以下示例有效(我删除了不必要的部分):

<!-- index.html -->
<meta charset="utf-8">

<script type="module">
  import { addTextToBody } from './module.js';

  addTextToBody('some text here');
</script>
Run Code Online (Sandbox Code Playgroud)
// module.js
export function addTextToBody(text) {
  const div = document.createElement('div');
  div.textContent = text;
  document.body.appendChild(div);
}
Run Code Online (Sandbox Code Playgroud)

上面提供的代码适用于 Firefox,但不适用于 Chrome。看来您正在使用 Chrome(我认为从您的错误消息来看)。Chrome严格禁止访问具有该file://协议的资源。有几种解决方案:

  1. 使用网络服务器(例如nginx)托管您的代码。
  2. 使用不同的网络浏览器(例如Firefox)。
  3. 完全禁用网络安全,请参阅此答案