如何在 Safari 上提供 ES6 模块?

How to serve ES6 modules on Safari?

我有一个关于在 Safari 中使用 ES6 模块的问题。这让我发疯,因为它阻止我与 Safari 用户共享我的网站。

我的 Web 应用程序和即将推出的 MWE 在以下环境中工作得很好

但是,我的 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' is not a valid JavaScript MIME type.

附加信息(不确定是否相关)

当我转到 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 但有一些问题。

到目前为止我尝试了什么

在网络开发中,我们使用 ES6 和 ES7 进行开发,但并非所有浏览器都支持这些。

为了在大多数浏览器中发布工作代码(Safari - Chrome - IE9)

与浏览器无关。您应该使用像 ( webpack - gulp - grant ) 这样的构建过程,或者使用像 ( React, Angular 和 VUE ) 这样的现有库

示例:开始使用 webpack https://webpack.js.org/guides/getting-started/

将通过将所有代码转换为 ES5 并捆绑该代码以确保减小卡盘尺寸来授予您完整的工作代码

我想我有一个解决办法:

将您的文件扩展名从 .js 更改为 .mjs。您可能还需要更新服务器的 mime types/extension 关联。我正在使用 apache2 - 我需要进入 /etc/mime.types 并修改行列表 js 以也包含 mjs (所以它现在将认为它是一个 application/javascript.)

我进行了最简单的测试——我需要在 Safari 上对我的网站进行更多测试,以验证它现在在所有预期的浏览器上都能正常工作。