Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

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

Chrome 80 fails to load the json with

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 fails in a similar way:

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

Is this behavior surmountable?

like image 508
wegry Avatar asked Feb 09 '20 19:02

wegry


2 Answers

You can't directly import JSON using an ES6 import. You need to export it from a JS file:

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

  console.log(mod)
})()
like image 121
Daniel Bank Avatar answered Oct 17 '22 05:10

Daniel Bank


Import Assertions are now stage 3 as of writing.

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.

like image 36
wegry Avatar answered Oct 17 '22 04:10

wegry