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 上尝试,我得到以下信息:
Access to Script at 'file:///Users/hasan/Documents/mjs/lib.mjs' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.
在 nodejs
中,我可以添加以下行,但我可以在我的文件中添加它吗,因为我知道它不是从服务器运行的!
response.setHeader('Access-Control-Allow-Origin', '*');
更新
我尝试从 this server 运行它,并设置CORS
,但出现以下错误:
Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
更新 2
当我将 .mjs
重命名为 .js
时,它对我有用,这是否意味着 .mjs
尚不支持!!
最佳答案
第一个错误输出是因为 JavaScript 模块是使用 CORS 获取的,我猜您没有使用设置正确 header 的服务器,如本文所述:https://developers.google.com/web/fundamentals/primers/modules
在您第二次尝试使用 200 OK Web Server extension for Chrome 时,由于缺少 MIME 类型支持,它尚不支持 JavaScript 模块。在开发人员的 Github 上有一个问题 https://github.com/kzahel/web-server-chrome/issues/133
关于javascript - 使用 JavaScript 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51090699/