Google Sheets iconSwift icon
Published at
Updated at
Reading time
2min

If you're using EcmaScript modules, you probably know the problem that you can't "just" import JSON files. To import and load a JSON file in an ES module, you have to do a "window.fetch dance" to request the file and parse it yourself. It's not great...

But there's hope! According to chromestatus.com, JSON Modules are shipping in Chrome 91. I gave it a quick try, and surprisingly, the following JavaScript code does not work.

<script type="module">
  import data from "./data.json";
  console.log(data);
</script>

It throws the following exception in Chrome 91:

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

I didn't have a detailed look at the spec discussion about this topic, but apparently, the new syntax to import JSON Modules is the following. 😲

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

console.log(data);

That's quite something, and I have to do some reading about it. But hey, anything that makes it easier to import JSON is more than welcome!

And when there's a solution in Chrome, it can't be long until it ships in Node.js because importing JSON files in Node ES modules is not great either. 🙈

Edit: Axel Rauschmayer shared that JSON import are based on import assertions and you can read more about it on his blog.

Related Topics

Related Articles