Dr. Axel Rauschmayer looks at JSON modules, which is already live in Chrome 91 (but nothing else). It looks just like an ES Modules-style import, only you asset the type at the end.
import configData from './config-data.json' assert {type: 'json'};
How nice is that? Once this makes its way across browsers, we’ve gone on a journey from “you’ll almost definitely want to use an Ajax library” because of the cross-browser complexity and weirdness of XMLHttpRequest
to the much nicer (but you still gotta write some code) fetch API, to a one-liner (if what you need is JSON data).
Snagging some JSON data seems like it should be as easy as a one-liner to me, and now it is. I like how the URL can be dynamic now too.
I need to read more into this.
Why would you need
assert {type: 'json'}
?We already have the type from the
.json
extensionAnswered in the article I link to:
I don’t know why I cannot answer to Chris’s comment, so I answer here.
“They look at content types”, “servers are responsible to provide it”. So why do I need to define? :) I’m client, not the server.
However, in an issue, Ryosuke Niwa (Apple) and Anne van Kesteren (Mozilla) proposed that security would be improved if some syntactic marker were required when importing JSON modules and similar module types which cannot execute code, to prevent a scenario where the responding server unexpectedly provides a different MIME type, causing code to be unexpectedly executed. The solution was to somehow indicate that a module was JSON, or in general, not to be executed, somewhere in addition to the MIME type.
Some developers have the intuition that the file extension could be used to determine the module type, as it is in many existing non-standard module systems. However, it’s a deep web architectural principle that the suffix of the URL (which you might think of as the “file extension” outside of the web) does not lead to semantics of how the page is interpreted. In practice, on the web, there is a widespread mismatch between file extension and the HTTP Content Type header. All of this sums up to it being infeasible to depend on file extensions/suffixes included in the module specifier to be the basis for this checking.
Can we have html imports next?
Unfortunately it seems that ship has sailed already