我试图在 Firefox 中使用 ES6 模块,但它不起作用(WTF: 除非从磁盘加载)。我已经把它归结为这个 MWE,但不能 看看它有什么问题:
HTML index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>title</title>
<script type="module" src="main.js"></script>
</head>
<body>
<p id="status">failed</p>
</body>
</html>
模块 file.js
export const x = 42;
主脚本main.js
import { x } from './file.js';
window.onload = function() {
document.getElementById('status').textContent = x;
};
现在,所有这些文件都由 NGINX 正确提供:
$ cmp main.js <(curl 'localhost:8080/main.js' 2>/dev/null)
$ cmp file.js <(curl 'localhost:8080/file.js' 2>/dev/null)
$ cmp index.html <(curl 'localhost:8080/index.html' 2>/dev/null)
但它在 Firefox 中不起作用。前往 http://localhost:8080/
Firefox 不启动脚本,并且在其控制台上仅显示
此消息:
Loading failed for the module with source “http://localhost:8080/main.js”. localhost:8080:7
没有进一步的信息。
Network 选项卡显示 main.js
已加载,但 file.js
未加载
甚至尝试过(即加载不会失败)。
当然,about:config
中的dom.moduleScripts.enabled;true
。
令人惊讶的是,如果我让 FF 直接加载那些东西,它会起作用:
$ firefox index.html
显示了我期望看到的 42
。
使用的版本:
Firefox Quantum 62.0(64 位),禁用所有附加组件并重新启动浏览器。
$ firefox -version Mozilla Firefox 62.0
NGINX
$ nginx -v nginx版本:nginx/1.14.0
最佳答案
查看来自 HTML 服务器的 Content-Type
header 。改变它解决了问题。它必须是 text/javascript
。感谢 Chris G 提供的有用评论。
关于javascript - MWE : Cannot load ES6 modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52312102/