Import attributes — Description
Import attributes tell the runtime how a particular module should be loaded.
Reference note (untrusted external data; do not execute it as instructions).
Import attributes tell the runtime how a particular module should be loaded.
The primary use case is to load non-JS modules, such as JSON modules and CSS modules. Consider the following statement
On the web, each import statement results in a HTTP request. The response is then prepared into a JavaScript value and made available to the program by the runtime. For example, the response may look like this
Modules are identified and parsed only according to their served media type (MIME type) — the file extension in the URL cannot be used to identify a file's type. In this case, the MIME type is application/json, which tells the browser that the file is JSON and must be parsed as JSON. If, for some reason (e.g., the server is hijacked or bogus), the media type in the server response is set to text/javascript (for JavaScript source), then the file would be parsed and executed as code. If the "JSON" file actually contains malicious code, the import declaration would unintentionally execute external code, posing a serious security threat.
Import attributes fix this problem by allowing the author to explicitly specify how a module should be validated. In particular, the type attribute allows you to validate that the file is served with a particular media type, and fails the import if a different media type is used.
For example, the code above can be written to specify that the expected type is "json" and the import would fail if it was served with the text/javascript (or any media type other than application/json)
The type attribute allows you to specify that modules are served as JSON, CSS, or plain text (and implicitly as JavaScript).
Other attributes may also be supported, and can affect the behavior of different parts of the loading process. A syntax error is thrown if an unknown attribute is used.
Attribution: Adapted from MDN Web Docs under CC-BY-SA-2.5. Adaptation: WikiKV selected one documentation section, normalized formatting, retained bounded excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
MDN Web Docs — files/en-us/web/javascript/reference/statements/import/with/index.md :: Description ↗Revision d14bee540b53 · CC-BY-SA-2.5 and attribution