如何在浏览器中使用 ES 模块?

How to work with ES Modules in the browser?

这是我的文件夹结构:

这些是我的文件:

/* index.html */
<body>
  <h1>Modules</h1>
  <script type="module" src="./index.js"></script>
</body>

// index.js
import fruits from "./fruits";

console.log(fruits);

// fruits.js
const arr = ["Mango", "Appple", "Banana", "Guava"];

export default arr;

我觉得一切都很好,但我仍然收到错误:net::ERR_ABORTED 404 (Not Found).

浏览器没有 Node.js 样式模块解析。您必须为模块指定确切的 URL。

import fruits from "./fruits.js";

并删除这个:

<script type="module" src="./fruits.js"></script>

…它不会任何事情。它只有在您将它导入其他地方时才有用。

试试看 从“./fruits.js”导入水果;

而不是 从“./fruits”导入水果;