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尚不支持!