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

标签 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>

还有 js:

export function addTextToBody(text) {

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

}

我收到这些错误:

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

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

我该如何解决这个问题?

最佳答案

  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>
// module.js
export function addTextToBody(text) {
  const div = document.createElement('div');
  div.textContent = text;
  document.body.appendChild(div);
}

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

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

关于由于错误,Javascript 导入模块到 index.html 未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343339/

相关文章:

javascript - 如何从 Controller 更新集合数组中的模型

javascript - jquery slider : how to separate two slider collection to act independently?

javascript - 向下滚动整个浏览器窗口

javascript - 为什么 `Object.keys/values/entries` 返回数组而 `Array...` 返回迭代器

javascript - 使用 switch case 跟踪数组的全局索引

Javascript:正则表达式转义空间

javascript - 如何生成 <form :input> tags dynamically from JS?

angularjs - ES6 Angularjs 指令,从调用 Controller 传入的函数没有构造函数变量

javascript - dispatchEvent(new Proxy(event, {}) 不起作用

javascript - 将字符串树转换为数组