2

我读了这个这个,并写了以下文件:

index.html

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>

<script type="module">
    (async () => {
      const moduleSpecifier = './lib.mjs';
      const {_default, repeat, shout} = await import(moduleSpecifier);
      repeat('hello');
      // → 'hello hello'
      document.getElementById("demo").innerHTML = shout('Dynamic import in action');
      // → 'DYNAMIC IMPORT IN ACTION!'

    })();
  </script>

</head>
<body>

<h1>This is a Heading</h1>
<p id="demo">Loading ..</p>

</body>
</html>

lib.mjs

export const repeat = (string) => `${string} ${string}`;
export function shout(string) {
  return `${string.toUpperCase()}!`;
}

但是一旦在chrome上尝试过,我得到了以下信息:

CORS 策略已阻止从源“null”访问“file:///Users/hasan/Documents/mjs/lib.mjs”处的脚本:响应无效。因此,Origin 'null' 不允许访问。

nodejs我可以添加以下行,但我可以将它添加到我的文件中,知道它不是从服务器运行的!

response.setHeader('Access-Control-Allow-Origin', '*');

更新

我尝试从该服务器运行它,并设置CORS,但得到以下错误:

加载模块脚本失败:服务器以非 JavaScript MIME 类型“”响应。根据 HTML 规范对模块脚本强制执行严格的 MIME 类型检查。

更新 2 当我重命名.mjsto时它对我有用.js,这是否意味着.mjs尚不支持!

4

1 回答 1

0

第一个错误输出是因为 JavaScript 模块是使用 CORS 获取的,我猜您没有使用设置正确标头的服务器,如本文所述:https ://developers.google.com/web/fundamentals/primers/模块

在您对 Chrome 的 200 OK Web 服务器扩展的第二次尝试中,由于缺少 MIME 类型支持,它还不支持 JavaScript 模块。开发人员的 Github 上有一个问题https://github.com/kzahel/web-server-chrome/issues/133

于 2018-10-08T12:34:28.803 回答