如何解决ES6 模块在 Safari 移动版 (iOS14.6) 上失败
我正在通过桌面(最新版 Chrome)和移动设备(带有 iOS 14.6 的 Safari)尝试 Javascript 模块,我的代码在桌面(标准浏览器或移动仿真模式)上运行良好,但在我的 iPhone 上失败。根据 https://caniuse.com/?search=modules
,尽管自 Safari iOS 11 起支持,但使用<script type="module">
导入的 JS 代码根本无法执行
下面的测试代码改编自 How to serve ES6 modules on Safari? ,托管在我的本地网络中的网络服务器上,移动和桌面客户端均可访问。对于移动调试,我使用本地复制的 https://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/ 版本在移动设备上呈现 console.log 命令。
test_ios.html
<html>
<head>
<Meta name="viewport" content="width=device-width,initial-scale=1.0">
<script>
console.log("Start of test_ios.html...");
</script>
<title>TESTS IOS</title>
<script src="/static/hnl.mobileConsole.1.3.js"></script>
<script nomodule src="/static/fallback.js"></script>
<script type="module">
console.log("Starting the main script.");
// The following line seems to cause an error in Safari only
import { TestClass } from './static/test_module.js';
// The rest is not executed due to the error
let test_class = new TestClass;
console.log("Done.");
</script>
<script>
console.log("End of test_ios.html...");
</script>
<body>
</body>
</html>
/static/test_module.js
export class TestClass {
constructor() {
console.log("Created a test class in test_module.js");
document.body.append("test_module.js");
}
}
/static/fallback.js
console.log("Fallback.js");
document.body.append("Fallback");
桌面上的结果,如预期
测试字符串 test_module.js
被写入网页,控制台中有以下几行:
--==## Mobile Console v1.3.5 active ##==--
End of test_ios.html...
Starting the main script.
Created a test class in test_module.js
Done.
iOS 14 上的结果 - 模块 JS 和回退均未执行
页面是空白的(没有执行 document.body.append(...)
)并且控制台中只有以下几行:
--==## Mobile Console v1.3.5 active ##==--
End of test_ios.html...
进一步的检查已经完成:
- 我嗅探了网络,发现移动设备请求了
/static/test_module.js
(没有请求fallback.js
)。 - 网络服务器返回的
/static/test_module.js
的内容类型似乎是一致的 (application/javascript; charset=utf-8
)。 - 将
test_module.js
重命名为test_module.mjs
没有帮助(结果与上述相同)
解决方法
我发现了这个问题:一旦调用 console.log
,以下库就会中断 Mobile Safari 中的 JS 执行:
<script src="/static/hnl.mobileConsole.1.3.js"></script>
删除此库包含或/和用 console.log
替换对 alert
的所有调用使上述代码按预期工作。示例代码还有一些小错误(例如没有 </head>
关闭),但这不是根本问题。
我检查了 jshint
是否会在 ES6 模式下捕获它,不幸的是没有成功。
下次移动 Safari 出现问题时的注意事项:用警告框乱扔 JS 代码,以查看它何时/何地中断:(
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。