【发布时间】:2020-09-18 02:19:48
【问题描述】:
我有一个关于在 Safari 中使用 ES6 模块的问题。这让我发疯,因为它阻止我与 Safari 用户共享我的网站。
我的网络应用程序和即将推出的 MWE 在以下环境中运行良好:
- Windows:Chrome、Edge 和 Firefox 均通过 Windows 本地服务器 (WAMP) 和我的 Web 服务器;
- 移动设备:Chrome、Firefox(Android 和 iOS 均适用)。即使是适用于 Android 的 Samsung Mobile 和 Opera 也能正常工作。
- MacOS:
- 在 Safari、Chrome 和 Firefox 上通过 Mac 本地服务器 (AMPPS);
- 通过我的网络服务器在 Chrome 和 Firefox 上。
但是,我的 Web 应用程序无法通过我的 Web 服务器在 MacOS Safari 中运行(目前我正在 Safari 13.0.4 上尝试此代码,但上述浏览器的所有现代版本都可以正常运行关于这个问题的方法相同)。同样,它不适用于最新版本的 iOS Safari。
MWE
./test_class.js
export class TestClass {
constructor() {
console.log("Created a test class");
}
}
./index.html
<!DOCTYPE html>
<script type="module">
console.log("Starting the main script.");
// The following line seems to cause an error in Safari only
import { TestClass } from './test_class.js';
// The rest is not executed due to the error
let test_class = new TestClass;
console.log("Done.");
</script>
控制台输出
当我从我的服务器加载 index.html 时,Safari 的控制台给了我错误
TypeError: 'text/html' 不是有效的 JavaScript MIME 类型。
其他信息(不确定是否相关)
当我转到 Safari 的资源部分时,确实有一个 test_class.js 条目,它不包含上面的代码,而是:
<html>
<body>
<script type="text/javascript" src="/aes.js" ></script>
<script>
function toNumbers(d)
// ...
function toHex()
// ...
var a = toNumbers("..."),
b = toNumbers("..."),
c = toNumbers("...");
document.cookie = "...";
location.href="http://www.my_super_website.com/test_class.js?i=1";
</script>
</body>
</html>
只有当我连接到我的服务器时才会发生这种情况。 location.href="http://www.my_super_website.com/test_class.js?i=1"; 这行有意义吗?我的理解是,此时 Safari 尝试加载 test_class.js 但有一些问题。
到目前为止我所做的尝试
- 如果我删除
import { TestClass } from './test_class.js';行,一切正常。 - 如果我将
import调用放在新的脚本文件中,然后在 html 文档中使用,也会出现同样的问题。 - 我验证了我命名文件 ./test_class.js 的方式是正确的,但由于这适用于大多数浏览器,我想这很好。
- 我正在使用免费托管解决方案 infinityfree.net,所以那里可能发生了什么事?
【问题讨论】:
-
您是否有机会使用 Babel、Webpack、Rollup 或 Parcel 等流行工具将您的 ES6 代码转换和捆绑到每个浏览器都可以使用/解析的东西?
-
我没有,我是 web 开发的新手,所以我没有这些经验。由于包括 Safari 在内的所有现代浏览器都与 ES6 模块兼容,我仍然认为这对我来说是一种有条理的编码方式。但如果没有人知道如何解决这个问题,我会研究这些工具!谢谢:)
-
嘿 - 在过去 6 周内这方面有什么进展吗?
标签: javascript html macos safari es6-modules