completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Import a CSS file as a sheetWrite import sheet from "./tea-card.css" with { type: "css" }, or the same with import(), and adopt the sheet you get.
  • 02
    Know what fails, and whereSpot a missing or wrong type, the old assert keyword, and a dropped @import, and know which browsers support CSS module scripts.
  • 03
    Ship it to every browserDetect support with a dynamic import, fall back to fetch() and replaceSync(), 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:

Import a CSS file and adopt the sheetPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 makes a module script. import lines only work in module scripts. import and export covers modules.
  • Line 3 imports menu.css. sheet is 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 a CSSStyleSheet, the same kind of object new CSSStyleSheet() makes.
  • Line 5 adds it to the page's adoptedStyleSheets, as in lesson 11.5. Line 6 prints rgb(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.

The import on line 3, import sheet from "./menu.css" with { type: "css" }, in steps. First the file, menu.css. Then the label the server sends with it, text/css, which matches type css. Then a CSSStyleSheet, the module's default export. An arrow goes down from it to document.adoptedStyleSheets, labelled line 5 adopts it. Under that: Green tea turns sea green.import sheet from "./menu.css" with { type: "css" }the filemenu.cssthe server's labeltext/cssthe default exportCSSStyleSheetline 5 adopts itdocument.adoptedStyleSheetsGreen tea turns sea green
The browser fetches 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.
Real-life analogyA sign from the print shop

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 CSSStyleSheet the import gives back
In real life: Hanging it in the window
In JavaScript: Adding it to adoptedStyleSheets
The main idea

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:

The import line on its ownJavaScript
import sheet from "./menu.css" with { type: "css" };

Line 1 has four pieces, from left to right:

  • import sheet names 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.
  • with starts 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:

Import a CSS file when a button is clickedPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 5 runs a function on each click. async lets it use await.
  • Line 6 calls import() with the file and { with: { type: "css" } }. await waits for the promise. module is the module object.
  • Line 7 prints Exports: default. The module has one export, named default.
  • Line 8 adopts module.default, the sheet. Line 9 prints rgb(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:

A card file and a page that import the same CSS filePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-card.js tab, 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.css again.
  • Line 9 collects the three shadow roots. Line 10 asks whether each root's sheet is the page's sheet. It prints Same 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.

On the left, two files import tea-card.css: tea-card.js and index.html. Arrows from both go to one window, modules, the page's module map, which holds one entry, tea-card.css, labelled one sheet object. From it, arrows go to three cards on the right, Green tea, Oolong, and Black tea, labelled three roots adopt it.tea-card.jsindex.htmltwo importsmodulestea-card.cssone sheet objectGreen teaOolongBlack teathree roots adopt it
The page's module map keeps one module per URL. Both imports find the same entry, so the card file, the page, and all three cards hold one sheet.
Real-life analogyThe stock room keeps one box of each

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.

Real-life analogyChecking the label on a delivery

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 type attribute
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:

Playground: the type on the import line
A page that loads tea-card.js, then asks if the card is definedPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The card loads.

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.

The page stays the same. Each choice changes line 1 of the tea-card.js tab. Open that tab to see it.
  • with { type: "css" }: Defined? true.
  • No attribute: Defined? false. The result's console warns Couldn'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.

Two dynamic imports that fail, caughtPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

A CSS module with an @import rulePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the menu.css tab, 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:

CSS module scripts in each browser
BrowserSinceWhat to know
Chrome and Edge123Chrome 93 to 125 used the old assert keyword. Chrome 126 removed it.
Firefox147Firefox 147 came out on January 13, 2026.
SafariNot yetSafari 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 CSSStyleSheet exists. Workers don't have it, so the HTML standard refuses type: "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:

Playground: with and without CSS module scripts
Try a CSS module, and fall back to fetch() and replaceSync()Pop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The import works.

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.

The second choice swaps line 5 for a line that throws. Everything else stays the same.
  • 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 catch block runs. Line 8 fetches menu.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 prints Loaded 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.

A fork. On the left, await import(). The upper path, labelled in Chrome and Firefox, goes to a card, CSS module, and on to a card, sheet, labelled adopted. The lower path, labelled in Safari, goes to fetch(), then to replaceSync(), labelled the catch block, and curves up to the same sheet card.await import()in Chrome and FirefoxCSS moduleadoptedsheetin Safarifetch()replaceSync()the catch block
Where CSS module scripts work, line 5 gives the sheet. Where the import fails, the catch block fetches the same file and fills a new sheet. Either way, line 13 adopts one sheet.
Real-life analogyThe lift, or the stairs

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(), then replaceSync()
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:

What four build tools do with a CSS module import
ToolWhat it does with the import
webpackSince webpack 5.109, it builds a CSSStyleSheet from the file with no setup. That code works in every major browser.
esbuildIt stops with an error. Mark the file external to leave the import for the browser, or add a plugin.
ViteIt has no built-in support. A plugin, vite-plugin-standard-css-modules, adds it.
RollupA 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:

What a build step puts in place of the import, shortenedPop out in the code editor (opens in a new tab)JavaScript
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.

Real-life analogyA menu translated before the visitors come

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() and replaceSync()
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:

CSS module scripts and CSS Modules, side by side
QuestionCSS module scriptsCSS 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:

Two declarative shadow roots with import and hrefPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Lines 2 and 8 write each card's shadow root in HTML.
  • Lines 3 and 9 are links with two addresses: href for today, import for the proposal.
  • Line 14 waits for the page's load event, 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.

Two halves. The left half, today, from href: the cards Green tea and Oolong each get a sheet of their own, sheet 1 and sheet 2, labelled two sheet objects. The right half, proposed, from import: the same two cards, and one sheet with an arrow to each, labelled one sheet object.today, from hrefGreen teasheet 1Oolongsheet 2two sheet objectsproposed, from importGreen teaOolongsheetone sheet object
Today Chrome loads 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:

Load tea-card.css once, then define the card with itPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-card.js tab, 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 removed assert. That line is a SyntaxError now. Write with.
  • "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.
  • "@import works 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.

Exercise 1 · Warm-upAn import line and an import() call

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>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upCount the rules

    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>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeThe card that never loads

      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>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeA night menu on demand

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeTwo files instead of @import

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeLoad once, even in the fallback

            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>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask: which type does the browser expect, and is this the same module?

              The CSS module scripts quiz · 8 questionsScore: first tries count
              1. Question 1 of 8What does import sheet from "./menu.css" with { type: "css" } put in sheet?

                Choose an answer to see the explanation.

              2. Question 2 of 8What does this page print about the module from a dynamic import?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              3. Question 3 of 8Two imports of the same file sit in one module. What does this page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              4. Question 4 of 8How many rules does this CSS module keep?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              5. Question 5 of 8A card file starts with import sheet from "./tea-card.css";, with no type. What happens?

                Choose an answer to see the explanation.

              6. Question 6 of 8An older tutorial writes assert { type: "css" }. What does Chrome do with it today?

                Choose an answer to see the explanation.

              7. Question 7 of 8Which browsers support CSS module scripts?

                Choose an answer to see the explanation.

              8. Question 8 of 8Why does feature detection use a dynamic import() and not a static import?

                Choose an answer to see the explanation.

              Key takeaways

              • import sheet from "./menu.css" with { type: "css" } loads a CSS file as one CSSStyleSheet, 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 type fails the import and the whole module. assert is a SyntaxError in Chrome now, and @import is dropped.
              • Chrome and Edge 123 and Firefox 147 support it. Safari doesn't yet.
              • For Safari, try import() and fall back to fetch() and replaceSync(), 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:

              Coming next: Fonts and shadow DOM. It shows how to load fonts for components with shadow roots.

              CompleteFrontend Clear concepts. Working examples.