[英]Dynamic or static import of json in browser with ESM
I have the following example running without the JS having a bundler on top of it.我有以下示例运行,而 JS 在它上面没有打包器。
// index.js
;(async () => {
const mod = await import('/index.json')
console.log(mod)
})()
{
"file": "index.json"
}
Chrome 80 fails to load the json with Chrome 80 无法加载 json
Failed to load module script: The server responded with a non-JavaScript MIME type of "application/json".
加载模块脚本失败:服务器以“application/json”的非 JavaScript MIME 类型响应。 Strict MIME type checking is enforced for module scripts per HTML spec.
每个 HTML 规范对模块脚本执行严格的 MIME 类型检查。
Firefox 73 fails in a similar way: Firefox 73 以类似的方式失败:
Loading module from “ http://127.0.0.1:8080/index.json ” was blocked because of a disallowed MIME type (“application/json”).
由于不允许的 MIME 类型(“application/json”),从“ http://127.0.0.1:8080/index.json ”加载模块被阻止。
Is this behavior surmountable?这种行为是可以克服的吗?
You can't directly import JSON using an ES6 import.您不能使用 ES6 导入直接导入 JSON。 You need to export it from a JS file:
您需要从 JS 文件中导出它:
// module.js
export default {
"foo": { "bar": "baz" }
};
// index.js
;(async () => {
const mod = await import('/module.js')
console.log(mod)
})()
Import Assertions are now stage 3 as of writing.在撰写本文时,导入断言现在处于第 3 阶段。
import json from "./foo.json" assert { type: "json" };
// or
import("foo.json", { assert: { type: "json" } });
would be the syntax for pulling in a JSON file with ESM.将是使用 ESM 拉入 JSON 文件的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.