Using CSS Module Scripts to import stylesheets
CSS module scripts are available by default in Chrome and Edge in version 93.
Support in Firefox and Safari is not yet available. Implementation progress can be tracked at the Gecko bug and WebKit bug, respectively.
- Familiarity with constructible stylesheets.
Using CSS module scripts
Import a CSS module script and apply it to a document or a shadow root like this:
The default export of a CSS module script is a constructable stylesheet whose contents are those of the imported file. Like any other constructable stylesheet, it is applied to documents or shadow roots using adoptedStyleSheets.
- Deduplication: if the same CSS file is imported from multiple places in an application, it will still only be fetched, instantiated, and parsed a single time.
- Security: modules are fetched with CORS and use strict MIME-type checking.
Import Assertions (what’s with the ‘assert’?)
Dynamically imported stylesheets
You can also import a CSS module using dynamic import, with a new second parameter for the type: ‘css’ import assertion:
@import rules not yet allowed
Currently CSS @import rules don’t work in constructable stylesheets, including CSS module scripts. If @import rules are present in a constructable stylesheet, those rules will be ignored.