CSS module scripts
Learn CSS module scripts: import a CSS file as a CSSStyleSheet, share it with every shadow root, and load it in browsers and bundlers without support.
- 01Import a CSS file as a sheetWrite
import sheet from "./tea-card.css" with { type: "css" }, or the same withimport(), and adopt the sheet you get. - 02Know what fails, and whereSpot a missing or wrong
type, the oldassertkeyword, and a dropped@import, and know which browsers support CSS module scripts. - 03Ship it to every browserDetect support with a dynamic import, fall back to
fetch()andreplaceSync(), and know what webpack, esbuild, and Vite do with the import.
What are CSS module scripts?
Leaf and Kettle's tea cards share one style sheet. In lesson 11.5, that sheet lives in tea-card.js, as CSS inside a JavaScript string. Ravi looks after the shop's design. He wants the CSS in a .css file, where his editor colors it and checks it.
Can a page load a CSS file straight into a style sheet object, the way it loads a JavaScript module?
Yes. A CSS module script is a CSS file you import like a JavaScript module: import sheet from "./menu.css" with { type: "css" }. The browser loads the file and gives you a CSSStyleSheet with its rules. You adopt it like any constructed sheet.
Chrome, Edge, and Firefox support it. Safari doesn't yet, so this lesson also shows how to ship it there. Here is the smallest page that uses one. Click the menu.css tab to see the file:
<p>Green tea</p><script type="module"> import sheet from "./menu.css" with { type: "css" }; console.log(sheet instanceof CSSStyleSheet); document.adoptedStyleSheets = [sheet]; console.log(getComputedStyle(document.querySelector("p")).color);</script>- Line 2 makes a module script.
importlines only work in module scripts. import and export covers modules. - Line 3 imports
menu.css.sheetis a name you choose for what comes back. - The end of line 3,
with { type: "css" }, is an import attribute. It tells the browser what kind of file to expect. - Line 4 prints
true. The sheet is aCSSStyleSheet, the same kind of objectnew CSSStyleSheet()makes. - Line 5 adds it to the page's
adoptedStyleSheets, as in lesson 11.5. Line 6 printsrgb(46, 139, 87), sea green.
In the result, Green tea is bold and sea green. The rules came from a file. No <style> or <link> element was made.
menu.css, checks the server's label against type: "css", and parses the rules into one CSSStyleSheet. Line 5 adopts it like any constructed sheet.Leaf and Kettle needs a new sign. The owner doesn't paint it herself. She sends the design file to the print shop and says, "A sign, please." The shop checks the file, prints it, and hands back a finished sign. She hangs it in the window.
- In real life: The design file
- In JavaScript:
menu.css - In real life: Saying "a sign, please"
- In JavaScript:
with { type: "css" } - In real life: The finished sign
- In JavaScript: The
CSSStyleSheetthe import gives back - In real life: Hanging it in the window
- In JavaScript: Adding it to
adoptedStyleSheets
import sheet from "./menu.css" with { type: "css" } loads a CSS file as one CSSStyleSheet. Adopt it in the page or in a shadow root. Every import of the same file gets the same sheet.
Lesson 1.2 listed CSS module scripts among the parts only some browsers have. This lesson goes deeper. The HTML standard calls the file a CSS module script, though it holds no script. MDN calls them CSS modules.
How do you import a CSS file as a stylesheet?
Take the import line from the first example apart:
import sheet from "./menu.css" with { type: "css" };Line 1 has four pieces, from left to right:
import sheetnames the module's default export, the one value it gives without a name. A CSS module has only that one export, and it's the sheet.from "./menu.css"says where the file is. A relative address starts from the file that holds the import, as for any module.withstarts the import attributes. They tell the browser how to load the module.{ type: "css" }says "this file is CSS". Without it, the browser expects JavaScript.
An import line runs before the rest of the module. So by line 4 of the first example, the file was loaded and parsed. The same with keyword loads JSON files, as module resolution and import maps shows.
Loading a stylesheet later with import()
Sometimes you only need styles later, when someone opens a panel or picks a theme. import() loads a module when your code asks. It gives back a promise, an object for a result that comes later. The import attributes go in a second argument. Dynamic import covers import().
Click Load the menu styles in the result:
<p>Green tea</p><button>Load the menu styles</button><script type="module"> const button = document.querySelector("button"); button.addEventListener("click", async () => { const module = await import("./menu.css", { with: { type: "css" } }); console.log("Exports:", Object.keys(module).join(", ")); document.adoptedStyleSheets = [module.default]; console.log(getComputedStyle(document.querySelector("p")).color); });</script>- Line 5 runs a function on each click.
asynclets it useawait. - Line 6 calls
import()with the file and{ with: { type: "css" } }.awaitwaits for the promise.moduleis the module object. - Line 7 prints
Exports: default. The module has one export, nameddefault. - Line 8 adopts
module.default, the sheet. Line 9 printsrgb(46, 139, 87).
Before the click, Green tea is plain. After it, Green tea is sea green. Why it matters: a page can wait to load styles until it needs them, and still get a ready sheet. import() works in a classic script too, without type="module".
Does every import get the same stylesheet?
Yes. The browser keeps one copy of each module per page, in a list called the module map. It finds each module by its full address, its URL, and its type. The first import loads the file. Every later import of that URL gets the same object.
Here the card file imports tea-card.css, and the page imports it too. Press Night menu in the result:
<tea-card>Green tea</tea-card><tea-card>Oolong</tea-card><tea-card>Black tea</tea-card><button>Night menu</button><script type="module"> import "./tea-card.js"; import sheet from "./tea-card.css" with { type: "css" }; const roots = [...document.querySelectorAll("tea-card")].map((card) => card.shadowRoot); console.log("Same sheet?", roots.every((root) => root.adoptedStyleSheets[0] === sheet)); document.querySelector("button").addEventListener("click", () => { sheet.replaceSync("p { color: gold; background: black; }"); console.log("Night:", getComputedStyle(roots[2].querySelector("p")).color); });</script>- In the
tea-card.jstab, line 1 imports the card's styles. Line 7 adopts the sheet in each card's shadow root. - In the page, lines 1 to 3 are three cards. Line 6 loads the card file. Line 7 imports
tea-card.cssagain. - Line 9 collects the three shadow roots. Line 10 asks whether each root's sheet is the page's
sheet. It printsSame sheet? true. - Line 12 replaces the rules of the page's sheet. Line 13 prints
Night: rgb(255, 215, 0), gold.
All three cards turn gold. Line 12 changed one object, and every card adopted that object. It's the night menu from lesson 11.5, with the sheet coming from a file.
At Leaf and Kettle, staff ask the stock room for supplies by shelf label. The first time someone asks for sea green ribbon, the stock room orders a box. After that, everyone who asks gets that same box. Nobody orders a second one.
- In real life: The shelf label
- In JavaScript: The file's URL
- In real life: The stock room's list
- In JavaScript: The page's module map
- In real life: The first order
- In JavaScript: The first import fetches and parses the file
- In real life: Everyone getting the same box
- In JavaScript: Every import getting the same sheet
Two things follow from this:
- Each file is fetched and parsed once, however many modules import it. web.dev's article calls this deduplication.
- The module stays for as long as the page is open. Importing the file again gives back the same sheet, even if the file changed on the server. To change the styles, change the sheet, as line 12 does.
Why it matters: every component in a library can import one shared file, and the page still holds one sheet.
What happens when the type is missing or wrong?
The import fails. A browser never guesses a module's type from the file name. A server sends each file with a label, its MIME type, like text/css. The browser checks that label against the type attribute. If they don't match, the import fails.
Leaf and Kettle orders tea leaves. A box arrives labelled "cleaning spray". Nobody brews it. They send it back. And when an order has no note at all, the shop expects its usual delivery: tea leaves.
- In real life: What you ordered
- In JavaScript: The
typeattribute - In real life: The label on the box
- In JavaScript: The MIME type the server sends,
text/css - In real life: Sending the box back
- In JavaScript: The import failing
- In real life: An order with no note
- In JavaScript: No
type: the browser expects JavaScript
Why so strict? MDN gives the reason. If a server sent JavaScript where you expected data, a loose check would run that code. With the type written down, the import fails instead.
Try it. Each choice changes line 1 of the tea-card.js tab:
<tea-card>Green tea</tea-card><script type="module" src="tea-card.js"></script><script type="module"> console.log("Defined?", customElements.get("tea-card") !== undefined);</script>Defined? true. The file is CSS, and line 1 says so. The browser hands tea-card.js a sheet, the file runs, and Green tea turns bold and sea green.
- with { type: "css" }:
Defined? true. - No attribute:
Defined? false. The result's console warnsCouldn't load the script tea-card.js. - with { type: "json" }:
Defined? false, with the same warning.
Line 4 of the page asks the registry for tea-card. When line 1 of the card file fails, the whole file fails. A module only runs once everything it imports has loaded. So customElements.define() never runs, and Green tea stays plain text. The CSS Modules explainer says so: a failed CSS import stops every module that depends on it.
DevTools' Console says why. With no attribute, Chrome prints Failed to load module script, then the reason: Expected a JavaScript-or-Wasm module script but the server responded with a MIME type of "text/css". With type: "json", it says it expected a JSON module script.
Catching a failed import()
A failed import() doesn't stop the module. It rejects its promise, so try and catch can handle it. try...catch covers them.
<script type="module"> try { await import("./tea-card.css"); } catch (error) { console.log("No type:", error.name); } try { await import("./tea-card.css", { with: { type: "CSS" } }); } catch (error) { console.log("Capital CSS:", error.message); }</script>- Line 3 imports the file with no attributes. The promise rejects, and line 5 prints
No type: TypeError. - Line 8 writes the type in capitals. Line 10 prints
Capital CSS: "CSS" is not a valid module type.The value must be"css", in small letters.
Older articles write assert { type: "css" }. Chrome 93 shipped CSS module scripts with that keyword. Chrome 126 removed it, so that line is now a SyntaxError, and its module doesn't run. Write with.
Does @import work in a CSS module?
No. An @import rule loads another CSS file from inside a sheet. A CSS module drops it:
<p>Green tea</p><script type="module"> import sheet from "./menu.css" with { type: "css" }; console.log("Rules:", sheet.cssRules.length); console.log(sheet.cssRules[0].cssText); document.adoptedStyleSheets = [sheet];</script>- In the
menu.csstab, line 1 is an@import. Line 2 is a sea green rule. - Line 4 prints
Rules: 1. Line 5 prints the rule that's left:p { color: seagreen; }.
DevTools' Console shows Chrome's warning: @import rules are not allowed here. Lesson 11.5 met the same warning with replaceSync(). Both come from the same steps. The HTML standard builds every CSS module as a constructed sheet, filled the way replaceSync() fills one. It leaves @import out until browser makers agree how it should work. To use two files, import both and adopt both. Exercise 5 does that.
Which browsers support CSS module scripts?
Chrome, Edge, and Firefox do. Safari doesn't. Read each row across:
| Browser | Since | What to know |
|---|---|---|
| Chrome and Edge | 123 | Chrome 93 to 125 used the old assert keyword. Chrome 126 removed it. |
| Firefox | 147 | Firefox 147 came out on January 13, 2026. |
| Safari | Not yet | Safari runs JSON modules, but a CSS module import fails. |
Without Safari, the feature isn't Baseline, the label lesson 1.2 explained. Firefox added it in Firefox 147. Older articles, like web.dev's, list only Chrome and Edge. Three details help when you plan:
- Safari understands
with. It has run JSON modules since Safari 17.2. Only the CSS type fails. - WebKit, Safari's engine, added CSS module scripts in October 2026, behind a setting that is off by default.
- CSS modules only load where
CSSStyleSheetexists. Workers don't have it, so the HTML standard refusestype: "css"there.
Why it matters: code that runs in Safari needs another way to load its styles. The next two sections give you two.
How do you fall back when CSS module scripts aren't supported?
Try the import, and catch the failure. In the catch block, load the same file as text, and fill a constructed sheet with it. You get a CSSStyleSheet either way.
Use import(), not an import line. A failed import line stops the whole module, as the playground above showed. A failed import() only rejects a promise. Switch between the two choices:
<p>Green tea</p><script type="module"> let sheet; try { sheet = (await import("./menu.css", { with: { type: "css" } })).default; console.log("Loaded as a CSS module script"); } catch { const response = await fetch("./menu.css"); sheet = new CSSStyleSheet(); sheet.replaceSync(await response.text()); console.log("Loaded with fetch() and replaceSync()"); } document.adoptedStyleSheets = [sheet]; console.log(getComputedStyle(document.querySelector("p")).color);</script>Loaded as a CSS module script. rgb(46, 139, 87). In Chrome or Firefox, line 5 imports menu.css as a sheet. The catch block never runs.
- Line 3 makes a variable for the sheet.
- Line 5 tries the CSS module. If it works, line 6 prints
Loaded as a CSS module script. - If line 5 fails, the
catchblock runs. Line 8 fetchesmenu.css.fetch()asks for a file and gives back a promise of the response. Fetch covers it. - Line 9 makes an empty sheet. Line 10 reads the response as text, and
replaceSync()puts its rules in the sheet. Line 11 printsLoaded with fetch() and replaceSync(). - Line 13 adopts the sheet, whichever line made it. Line 14 prints
rgb(46, 139, 87).
The second choice swaps line 5 for a line that throws, the way the import fails in Safari. The page prints Loaded with fetch() and replaceSync(), and Green tea is still sea green.
catch block fetches the same file and fills a new sheet. Either way, line 13 adopts one sheet.Leaf and Kettle's café is on the second floor. You press the lift button. If the lift has an out of order sign, you take the stairs. Either way, you sit at the same table.
- In real life: Pressing the lift button
- In JavaScript:
await import(…, { with: { type: "css" } }) - In real life: An out of order sign
- In JavaScript: The promise rejecting
- In real life: Taking the stairs
- In JavaScript:
fetch(), thenreplaceSync() - In real life: The same café table
- In JavaScript: A sheet with the same rules
The two paths differ in two ways:
fetch()has no module map. Each call fetches the file again and makes a new sheet. So load the sheet once, and share it. Exercise 6 shows the bug.- The fallback needs constructable stylesheets, so it works from Safari 16.4.
Do bundlers support CSS module scripts?
A bundler is a build tool. It joins your modules into fewer files before you ship them. Some bundlers turn a CSS module import into plain JavaScript that every browser runs. Others can't yet. Read each row across:
| Tool | What it does with the import |
|---|---|
| webpack | Since webpack 5.109, it builds a CSSStyleSheet from the file with no setup. That code works in every major browser. |
| esbuild | It stops with an error. Mark the file external to leave the import for the browser, or add a plugin. |
| Vite | It has no built-in support. A plugin, vite-plugin-standard-css-modules, adds it. |
| Rollup | A plugin, rollup-plugin-import-css, turns the import into a CSSStyleSheet. |
What goes in place of the import? webpack's code and the Vite plugin's docs both make a constructed sheet and fill it with replaceSync(). In short:
const sheet = new CSSStyleSheet();
sheet.replaceSync("p { color: seagreen; font-weight: bold; }");
console.log(sheet.cssRules[0].cssText);- Line 1 makes the sheet. Line 2 fills it with the file's rules.
- Line 3 prints the rule:
p { color: seagreen; font-weight: bold; }.
That's the shape of the kit's tea-card.js from lesson 11.5. So you can write with { type: "css" } in your source, and ship these two lines. webpack's guide shows the import working with no setup.
esbuild knows only the types json, text, and bytes. For css, it stops with Importing with a type attribute of "css" is not supported. Mark the file external, as in --external:./tea-card.css, and esbuild leaves the import as written, for the browser.
Vite's docs give two ways to import CSS. A plain import "./menu.css" adds the rules to the page in a <style> element. Adding ?inline gives you the CSS as a string. Neither gives a sheet. The request for CSS import attributes, issue #17700, is open.
Leaf and Kettle writes its menu in its own words. Before a tour group arrives, a translator rewrites it so every visitor can read it. The dishes stay the same.
- In real life: The menu in the café's own words
- In JavaScript: Your source, with
with { type: "css" } - In real life: The translator
- In JavaScript: The bundler or its plugin
- In real life: The translated menu
- In JavaScript:
new CSSStyleSheet()andreplaceSync() - In real life: Every visitor can read it
- In JavaScript: It runs in Safari too
CSS module scripts aren't CSS Modules
The names are close, but the ideas aren't. CSS Modules, with a capital M, is a bundler feature for files named like card.module.css. It renames each class so two files can't clash. Read each row across:
| Question | CSS module scripts | CSS Modules |
|---|---|---|
| Who runs it? | The browser. | A bundler, like Vite or webpack. |
| What does the import give you? | One CSSStyleSheet. | An object of class names, like classes.red. |
| How do you write it? | import sheet from "./card.css" with { type: "css" } | A file named card.module.css, imported with import classes from "./card.module.css" |
| What is it for? | Sharing one sheet with shadow roots. | Keeping class names from clashing on one page. |
What is the <link rel="stylesheet" import> proposal?
Everything so far needs JavaScript. A declarative shadow root doesn't. It's a shadow root written in HTML, with <template shadowrootmode="open">, which lesson 1.2 showed. It has no script to adopt a sheet. So each root needs its own <style> or <link>, as in lesson 11.1, and each gets its own sheet.
A proposal would fix that. It adds an import attribute to a stylesheet <link>. The link would load the file as a CSS module, through the module map. Every link that names the same file would share one sheet, with no script. It's pull request #12860 to the HTML standard, from issue #10673. It's still open, and no browser ships it.
Edge's explainer keeps href as a fallback. A browser that doesn't know import loads href the classic way. This page has both:
<tea-card> <template shadowrootmode="open"> <link rel="stylesheet" href="tea-card.css" import="tea-card.css"> <p>Green tea</p> </template></tea-card><tea-card> <template shadowrootmode="open"> <link rel="stylesheet" href="tea-card.css" import="tea-card.css"> <p>Oolong</p> </template></tea-card><script> addEventListener("load", () => { const links = [...document.querySelectorAll("tea-card")].map((card) => card.shadowRoot.querySelector("link")); console.log("Same sheet?", links[0].sheet === links[1].sheet); });</script>- Lines 2 and 8 write each card's shadow root in HTML.
- Lines 3 and 9 are links with two addresses:
hreffor today,importfor the proposal. - Line 14 waits for the page's
loadevent, which comes after both style sheets load. Line 16 compares the two links' sheets.
It prints Same sheet? false. Chrome ignores import and loads href, so each card gets a sheet of its own. Under the proposal, both links would give the same sheet.
href, so each declarative shadow root gets its own sheet. Under the proposal, import would go through the module map, and both roots would share one.An earlier version of the idea was an attribute on the template, shadowrootadoptedstylesheets. Chrome ran an origin trial of it from Chrome 148 to 153. An origin trial lets real sites try a feature before it ships. After feedback, its authors switched to <link>. Chrome Platform Status lists no position from Firefox or Safari on either idea.
Why it matters: until a browser ships it, a server-rendered component that shares one sheet still needs a script.
Loading every tea card's styles from tea-card.css
Now put it together. The card file takes its sheet as an argument, so the page decides how to load it. The page tries a CSS module, falls back to fetch(), and gives every card the one sheet:
<tea-card>Green tea</tea-card><tea-card>Oolong</tea-card><tea-card>Black tea</tea-card><script type="module"> import { defineTeaCard } from "./tea-card.js"; let sheet; try { sheet = (await import("./tea-card.css", { with: { type: "css" } })).default; } catch { sheet = new CSSStyleSheet(); sheet.replaceSync(await (await fetch("./tea-card.css")).text()); } defineTeaCard(sheet); const roots = [...document.querySelectorAll("tea-card")].map((card) => card.shadowRoot); console.log("Same sheet?", roots.every((root) => root.adoptedStyleSheets[0] === sheet));</script>- In the
tea-card.jstab, line 1 exports a function that takes the sheet. Line 6 adopts it in each card's root. Line 10 registers the tag. - In the page, line 5 imports the function.
- Lines 7 to 13 are the fallback from above, in short. Line 12 fetches the file, reads its text, and fills the sheet, all in one line.
- Line 14 defines the card with the sheet. The three cards on lines 1 to 3 upgrade.
- Line 17 prints
Same sheet? true.
Press Edit & run and swap line 9 for the throwing line from the playground: throw new TypeError("This browser has no CSS module scripts");. The page still prints Same sheet? true. The fallback made one sheet, and all three cards share it.
One rule applies when a loader sits inside a component's own file. import() looks for the file next to that module. fetch() looks next to the page. So build the address for fetch() from the module's own: new URL("./tea-card.css", import.meta.url). import.meta.url is the module's full address.
And the kit? Its tea-card.js keeps the constructed sheet from lesson 11.5. That's the code a build step makes from tea-card.css, and it already works in Safari. A kit that keeps its CSS in files writes with { type: "css" } in its source, and ships its build.
Common mix-ups
- "CSS module scripts are CSS Modules." No. CSS module scripts give you one
CSSStyleSheet, in the browser. CSS Modules is a bundler feature that renames class names. - "
assert { type: "css" }still works." No. Chrome 126 removedassert. That line is aSyntaxErrornow. Writewith. - "The browser can tell it's CSS from the file name." No. Without
type, it expects JavaScript, and the import fails. - "Each import makes a new copy of the sheet." No. A page keeps one module per URL. Every import gets the same sheet.
- "CSS module scripts only work in Chrome." No. Firefox added them in Firefox 147. Safari is the one without them.
- "
@importworks inside a CSS module." No. Chrome drops it, with a warning. Import each file instead. - "Importing the file again picks up my edits." No. The module stays for as long as the page is open. Change the sheet with
replaceSync().
Practice exercises
Answer first, then use the hints. The pages run live, so you can check yourself.
What does the console print?
<script type="module"> import first from "./menu.css" with { type: "css" }; const second = (await import("./menu.css", { with: { type: "css" } })).default; console.log(first === second);</script>true. The page keeps one module per URL and type, so the import line and import() both get the same sheet.
The menu.css tab has an @import and two rules. What does the console print?
<script type="module"> import sheet from "./menu.css" with { type: "css" }; console.log(sheet.cssRules.length);</script>2. Chrome drops the @import rule, with a warning in DevTools' Console, and keeps the other two.
The page prints Defined? false. Fix tea-card.js. What does your fixed page print?
<tea-card>Green tea</tea-card><script type="module" src="tea-card.js"></script><script type="module"> console.log("Defined?", customElements.get("tea-card") !== undefined);</script><tea-card>Green tea</tea-card><script type="module" src="tea-card.js"></script><script type="module"> console.log("Defined?", customElements.get("tea-card") !== undefined);</script>With no type, the browser expects JavaScript and gets text/css, so the import and the whole card file fail. With the type, the file runs, and the page prints Defined? true.
Clicking Night menu prints rgb(0, 0, 0). Make the click load night.css and adopt it. What does the console print after your fix?
<p>Green tea</p><button>Night menu</button><script type="module"> document.querySelector("button").addEventListener("click", async () => { // Import night.css as a style sheet here, and adopt it on the page. console.log(getComputedStyle(document.querySelector("p")).color); });</script><p>Green tea</p><button>Night menu</button><script type="module"> document.querySelector("button").addEventListener("click", async () => { const module = await import("./night.css", { with: { type: "css" } }); document.adoptedStyleSheets = [module.default]; console.log(getComputedStyle(document.querySelector("p")).color); });</script>The click imports night.css as a CSS module and adopts its sheet. The paragraph turns gold, and the console prints rgb(255, 215, 0).
menu.css tries to pull in base.css with @import, and the page prints normal. Make both files apply. What does your fixed page print?
<p>Green tea</p><script type="module"> import menu from "./menu.css" with { type: "css" }; document.adoptedStyleSheets = [menu]; console.log(getComputedStyle(document.querySelector("p")).fontStyle);</script><p>Green tea</p><script type="module"> import base from "./base.css" with { type: "css" }; import menu from "./menu.css" with { type: "css" }; document.adoptedStyleSheets = [base, menu]; console.log(getComputedStyle(document.querySelector("p")).fontStyle);</script>A CSS module drops @import, so the italic rule never loaded. Importing both files gives two sheets, and adopting both applies both. The page prints italic.
Line 4 makes loadSheet() act like Safari, and the page prints Same sheet? false. Change lines 13 and 14 so both get one sheet. What does your fixed page print?
<script type="module"> async function loadSheet(url) { try { throw new TypeError("This browser has no CSS module scripts"); return (await import(url, { with: { type: "css" } })).default; } catch { const sheet = new CSSStyleSheet(); sheet.replaceSync(await (await fetch(url)).text()); return sheet; } } const first = await loadSheet("./menu.css"); const second = await loadSheet("./menu.css"); console.log("Same sheet?", first === second);</script><script type="module"> async function loadSheet(url) { try { throw new TypeError("This browser has no CSS module scripts"); return (await import(url, { with: { type: "css" } })).default; } catch { const sheet = new CSSStyleSheet(); sheet.replaceSync(await (await fetch(url)).text()); return sheet; } } const loading = loadSheet("./menu.css"); const first = await loading; const second = await loading; console.log("Same sheet?", first === second);</script>fetch() has no module map, so each call made a new sheet. With one call, both awaits get the same promise, so the page prints Same sheet? true.
Check your understanding
For each question, ask: which type does the browser expect, and is this the same module?
Question 1 of 8What does
import sheet from "./menu.css" with { type: "css" }put insheet?Choose an answer to see the explanation.
Question 2 of 8What does this page print about the module from a dynamic import?
Read the code, then predict<script type="module"> const module = await import("./menu.css", { with: { type: "css" } }); console.log(Object.keys(module).length); </script>Choose an answer to see the explanation.
Question 3 of 8Two imports of the same file sit in one module. What does this page print?
Read the code, then predict<script type="module"> import one from "./menu.css" with { type: "css" }; import two from "./menu.css" with { type: "css" }; console.log(one === two); </script>Choose an answer to see the explanation.
Question 4 of 8How many rules does this CSS module keep?
Read the code, then predict<script type="module"> // menu.css: @import url("fonts.css"); p { color: seagreen; } import sheet from "./menu.css" with { type: "css" }; console.log(sheet.cssRules.length); </script>Choose an answer to see the explanation.
Question 5 of 8A card file starts with
import sheet from "./tea-card.css";, with notype. What happens?Choose an answer to see the explanation.
Question 6 of 8An older tutorial writes
assert { type: "css" }. What does Chrome do with it today?Choose an answer to see the explanation.
Question 7 of 8Which browsers support CSS module scripts?
Choose an answer to see the explanation.
Question 8 of 8Why does feature detection use a dynamic
import()and not a staticimport?Choose an answer to see the explanation.
Key takeaways
import sheet from "./menu.css" with { type: "css" }loads a CSS file as oneCSSStyleSheet, its only export. Adopt it like any constructed sheet.import()takes the same attribute in a second argument,{ with: { type: "css" } }.- A page keeps one module per URL, so every import of a file gets the same sheet.
- A missing or wrong
typefails the import and the whole module.assertis aSyntaxErrorin Chrome now, and@importis dropped. - Chrome and Edge 123 and Firefox 147 support it. Safari doesn't yet.
- For Safari, try
import()and fall back tofetch()andreplaceSync(), or let a bundler like webpack build the sheet. <link rel="stylesheet" import>is a proposal for sharing one sheet with declarative shadow roots. No browser ships it.
Remember the one-liner.
Import the file with its type, adopt the one sheet you get, and keep a fallback for Safari.
Sources
The facts on this page come from these standards, docs, and source files:
- Import attributes: CSS modules, MDN.
- HTML Standard: creating a CSS module script, WHATWG.
- HTML Standard: the module type allowed steps, WHATWG.
- CSS Modules V1 Explainer, Dan Clark, WICG.
- Using CSS module scripts to import stylesheets, Dan Clark, web.dev.
- Deprecate and remove import assertion 'assert' syntax, Chrome Platform Status.
- Firefox 147 release notes for developers, MDN.
- Implement CSS module scripts (commit b1913f6), WebKit.
- import.meta, MDN.
- Native CSS: import a constructable stylesheet, webpack.
- CssGenerator.js (webpack v5.113.0), webpack.
- bundler.go (esbuild v0.28.2), esbuild.
- Features: CSS, Vite.
- Support Vanilla JS CSS Modules / CSS import attributes, #17700, Vite.
- vite-plugin-standard-css-modules, Gracile.
- rollup-plugin-import-css, Jacob Leeson.
- Module Stylesheet <link> tags, #12860, WHATWG.
- Style Module Imports via <link> Elements, #10673, WHATWG.
- Declarative Shadow DOM Style Sharing, Microsoft Edge explainers.
- Declarative Shadow DOM 'shadowrootadoptedstylesheets', Chrome Platform Status.
Coming next: Fonts and shadow DOM. It shows how to load fonts for components with shadow roots.