Sub topic 15
Beyond JSON: Other Module Types
The type attribute is not only for JSON. Import attributes give the module loader a general way to answer "what kind of resource is this, and how should I turn it into a module?" JSON was the first answer. This chapter covers the second one that browsers ship, CSS module scripts. It also looks at the types runtimes and proposals are adding, and the rules that apply to every module type, so you can reason about types this tutorial does not list.
The chapter assumes you have read the earlier chapters on why the type attribute is required, caching and mutation, and browser MIME handling.
The general rule: type selects a module kind
Every module type works the same way:
- The importer declares the expected kind with
with { type: "..." }. - The host (the browser, Node.js, Deno, or Bun) fetches the resource and checks that what it received matches the declared kind. In browsers that check uses the MIME type.
- The host builds a synthetic module, which is a module whose exports the host creates directly instead of getting them by running JavaScript. Almost every non-JavaScript type exposes a single default export.
- The module is cached under the URL and the type.
Two consequences follow from this rule.
- Type is part of the cache key. The HTML specification keys its module map by URL and module type. Importing the same URL once as
"json"and once as"css"produces two separate fetch-and-check attempts, and at least one of them fails the MIME check. It never quietly reuses the other entry. - Unknown types fail loudly. A host rejects a type it does not support. It also rejects attribute keys it does not recognize. In both cases the module graph fails to load, and the host does not fall back to treating the file as JavaScript. That behavior is what keeps the security guarantee from the earlier chapter intact as new types are added.
CSS module scripts
A CSS module script imports a stylesheet as a module. Its default export is a CSSStyleSheet object, a constructable stylesheet that you attach to a document or shadow root through adoptedStyleSheets.
/* button.css */
.btn {
padding: 0.5rem 1rem;
border-radius: 4px;
background: rebeccapurple;
color: white;
}// main.js (loaded with <script type="module" src="main.js">)
import sheet from "./button.css" with { type: "css" };
console.log(sheet instanceof CSSStyleSheet); // true
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];Importing the file only parses the CSS. Nothing applies to the page until you add the sheet to an adoptedStyleSheets array, and loading a <link> element does not do this either.
Why CSS modules suit web components
Shadow DOM isolates a component's styles. Without CSS modules, each component instance usually injects its own <style> element, so the browser parses the same CSS once per instance. A CSS module is parsed once and cached, and every shadow root can adopt the same CSSStyleSheet object.
// fancy-button.js
import sheet from "./button.css" with { type: "css" };
class FancyButton extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
root.adoptedStyleSheets = [sheet];
const button = document.createElement("button");
button.className = "btn";
const slot = document.createElement("slot");
button.append(slot);
root.append(button);
}
}
customElements.define("fancy-button", FancyButton);Shared mutable instance, again
The caching chapter showed that every importer of a JSON module sees the same object. The same holds for CSS, and the effect is visible on screen. If one module changes the shared sheet, every document and shadow root that adopted it updates at once.
import sheet from "./button.css" with { type: "css" };
// Changes the color of every fancy-button on the page, in every shadow root
sheet.insertRule(".btn { background: darkgreen; }", sheet.cssRules.length);Sometimes this is what you want, for example a theme switch. If you need per-instance changes, copy the rules into a new sheet:
import sheet from "./button.css" with { type: "css" };
function cloneSheet(source) {
const copy = new CSSStyleSheet();
const text = Array.from(source.cssRules, (rule) => rule.cssText).join("\n");
copy.replaceSync(text);
return copy;
}
const privateSheet = cloneSheet(sheet);
privateSheet.insertRule(".btn { background: crimson; }", privateSheet.cssRules.length);CSS module gotchas
| Behavior | What happens | What to do |
|---|---|---|
| `@import` inside the CSS file | Constructable stylesheets do not support `@import`, so the rule is ignored and the console logs a warning | Import each stylesheet as its own module and adopt them all |
| Server sends the wrong MIME type | The import fails; the response must be `text/css` | Fix the server's content type, as with JSON |
| Named imports | They fail at link time; the only export is `default` | Use `import sheet from ...` |
| Relative `url()` values | They resolve against the CSS file's URL, not the page's | Keep asset paths relative to the stylesheet |
| Node.js | Node does not support `type: "css"` | Use a bundler, or keep CSS imports in browser-only code |
Feature detection and fallback
At the time of writing, Chromium-based browsers ship CSS module scripts, and other engines have been adding them. Check a current compatibility table before you rely on them. A failed static import breaks the whole module graph, so if support is uncertain, load the stylesheet with a dynamic import() and fall back to fetching the CSS yourself:
async function loadSheet(url) {
try {
const module = await import(url, { with: { type: "css" } });
return module.default;
} catch {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status} for ${url}`);
}
const sheet = new CSSStyleSheet();
await sheet.replace(await response.text());
return sheet;
}
}
const sheet = await loadSheet(new URL("./button.css", import.meta.url).href);
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];The fallback loses the module cache, so each call creates a new sheet. If you call it more than once for the same URL, store the result in a Map keyed by URL.
Types beyond the web platform standard
The import attributes mechanism leaves the set of types open, and runtimes have used that freedom. These types are not portable. Code that uses them runs only on the runtime or bundler that defines them.
| Type | Where it works (at the time of writing) | Default export |
|---|---|---|
| `"json"` | Browsers, Node.js, Deno, Bun | Parsed JSON value |
| `"css"` | Browsers (support varies by engine) | `CSSStyleSheet` |
| `"text"` | Bun; Deno behind an unstable flag; TC39 proposal work | File contents as a string |
| `"bytes"` | Deno behind an unstable flag; TC39 proposal (Import Bytes) | `Uint8Array` of the file |
| `"toml"`, `"file"`, `"sqlite"` | Bun only | Parsed TOML, a file path, or a database handle |
Here is a Bun-specific example. It fails in browsers and Node.js:
// Runs in Bun only
import readme from "./README.md" with { type: "text" };
console.log(readme.split("\n")[0]);Bundlers often provide the same features through a URL query instead of an attribute. Vite, for example, uses import text from "./file.txt?raw". A query string changes the URL, while an attribute leaves the URL alone. If you write the attribute form, your code stays closer to the direction the standards are taking, but you still need a build step to run it anywhere except the one runtime that supports it.
WebAssembly takes a different route
You might expect with { type: "webassembly" }. The current standards track uses a different mechanism instead. The ES module integration for WebAssembly lets a .wasm file be imported as a module based on its MIME type, application/wasm. Because WebAssembly can execute code, it does not need the "this must not run code" guarantee that the type attribute provides. A related proposal, source phase imports, adds import source mod from "./lib.wasm" to get a compiled WebAssembly.Module without instantiating it. Support is still partial and often behind flags, so for now treat WebAssembly.instantiateStreaming(fetch(url)) as the portable option.
Choosing a module type
- Use
"json"anywhere. It is the only type supported across all major environments. - Use
"css"for browser code, especially web components, and include a fallback until your target browsers all support it. - Use runtime-specific types such as
"text","toml", and"sqlite"only in code that will never leave that runtime, or that a bundler rewrites. - Keep the resource in a separate cache entry when you need a private copy. That means cloning a CSS sheet, as shown above, or reading the file yourself, as the alternatives chapter describes.
Exercise
A page runs import a from "./theme.css" with { type: "css" }; in one module and import b from "./theme.css" with { type: "css" }; in another. Module two then calls b.replaceSync(".x { color: red; }"). What happens to elements styled by a sheet that adopted a, and why?
Show answer
Their styles change too. Both imports share one URL and one type, so they resolve to the same cache entry, and a and b are the same CSSStyleSheet object. replaceSync replaces that shared sheet's rules, and every document or shadow root that adopted it updates.
Exercise
A team's server sends theme.css with the content type text/plain. What does import sheet from "./theme.css" with { type: "css" } do, and does the fallback loadSheet function from this chapter catch the problem?
Show answer
The static import fails because a CSS module script requires a text/css response, so the importing module graph does not load. loadSheet catches the import error and falls back to fetch. response.ok is true and response.text() does not check the content type, so the fallback applies the CSS without reporting the misconfiguration. To catch it, add a content-type check to the fallback.
Exercise
Why does WebAssembly's ES module integration not use with { type: "webassembly" }, when JSON and CSS need a type attribute?
Show answer
The type attribute exists so that a server cannot turn an import the developer expects to be inert data into executable code. WebAssembly is executable code already, so the importer trusts it the way it trusts JavaScript, and the host identifies it by its application/wasm MIME type.