使用 ESM 在浏览器中动态或静态导入 json

Dynamic or static import of json in browser with ESM

我有以下示例 运行 没有 JS 在它上面有一个捆绑器。

// index.js
;(async () => {
  const mod = await import('/index.json')

  console.log(mod)
})()
{
  "file": "index.json"
}

Chrome 80 加载 json 与

失败

Failed to load module script: The server responded with a non-JavaScript MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec.

Firefox 73 以类似的方式失败:

Loading module from “http://127.0.0.1:8080/index.json” was blocked because of a disallowed MIME type (“application/json”).

这种行为可以克服吗?

您不能使用 ES6 导入直接导入 JSON。您需要从 JS 文件导出它:

// module.js
export default {
  "foo": { "bar": "baz" }
};
// index.js
;(async () => {
  const mod = await import('/module.js')

  console.log(mod)
})()

Import Assertions 截至撰写本文时已进入第 3 阶段。

import json from "./foo.json" assert { type: "json" };

// or

import("foo.json", { assert: { type: "json" } });

将是使用 ESM 拉入 JSON 文件的语法。