This article teaches you how to import CSS like JS modules

This article teaches you how to import CSS like JS modules

Preface

The just released Chrome 93 version has an exciting new feature: CSS Module Script, which allows you to load CSS styles like importing a JavaScript module.

You can then apply CSS styles to the document and shadow dom in the same way as a Constructable Stylesheet, which is more convenient and efficient than other ways of loading CSS.

What are constructible style sheets?

Before understanding CSS Module Script, let's first understand what a constructible stylesheet is. As it implies, it is designed to be directly constructible by CssStyleSheet and can be used in both document and shadow DOM.

Using a constructible stylesheet:

  • Construct a style sheet via new CSSStyleSheet()
  • Changing the configurable style sheet
  • Using constructible style sheets via adoptedStyleSheets

The API for changing the constructible style sheet is as follows:

  • insertRule(rule, index) inserts rule into the cssRules attribute
  • deleteRule(rule, index) Delete rule from cssRules property
  • replace(text) asynchronously replaces cssRules
  • replaceSync(text) Synchronous replacement
// Construct the CSSStyleSheet
const stylesheet = new CSSStyleSheet();
 
// Add some CSS
stylesheet.replaceSync('body { background: #000 !important; }')
// OR stylesheet.replace, which returns a Promise instead
 
// Tell the document to adopt your new stylesheet.
// Note that this also works with Shadow Roots.
document.adoptedStyleSheets = [...document.adoptedStyleSheets, stylesheet];

Using CSS Module Script

Introducing CSS Module Script will act on document and shadow dom, as follows:

import sheet from './styles.css' assert { type: 'css' };
document.adoptedStyleSheets = [sheet];
shadowRoot.adoptedStyleSheets = [sheet];

The default export of CSS Module Script is a constructible style sheet, and like any other constructible style sheet, it uses adoptedstylesheet to act on document and shadow dom.

Unlike other ways of including CSS using JavaScript, you don't need to create a <script> tag, nor do you need to insert the CSS into the obfuscated JavaScript.

CSS Modules also have the same advantages as JavaScript Modules:

  • Deduplication: If you import the same CSS file from multiple locations in your app, it will still only be fetched, instantiated, and parsed once.
  • Consistent ordering: If you import a JavaScript runtime, it can depend on the stylesheets already being parsed.
  • Security: Modules are loaded using CORS and use strict MIME type checking.

What are import assertions?

The assert {type: 'css'} part of the import statement is an import assertion, which is required; without it, CSS will be considered a normal JavaScript module and will fail to import if the imported file has a non-JavaScript MIME type.

import sheet from './styles.css'; // Failed to load module script:
                                  // Expected a JavaScript module
                                  // script but the server responded
                                  // with a MIME type of "text/css".

Dynamic import of style sheets

Similar to dynamic import of JavaScript modules, you can also import CSS modules using dynamic import:

const cssModule = await import('./style.css', {
  assert: { type: 'css' }
});
document.adoptedStyleSheets = [cssModule.default];

There is a pitfall here that needs to be noted. What is added to adoptedstylesheet is not the cssModule itself, but cssModule.default.

@import rules are not yet supported

Currently, the rules for CSS @import do not apply to constructible stylesheets, including CSS Module Scripts. If a CSS module contains @import rules, they will be ignored.

/* atImported.css */
div {
    background-color: blue;
}
/* styles.css */
@import url('./atImported.css'); /* Ignored in CSS module */
div {
    border: 1em solid green;
}
<!-- index.html -->
<script type="module">
    import styles from './styles.css' assert { type: "css" };
    document.adoptedStyleSheets = [styles];
</script>
<div>This div will have a green border but no background color.</div>

Currently, Firefox and Safari browsers are not supported, but it can be expected in the future~

Summarize

This is the end of this article on how to import CSS like importing JS modules. For more related content like importing JS modules and importing CSS, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of JS module import and export
  • Tutorial on exporting and importing in javascript to achieve modular management

<<:  How to automatically backup mysql remotely under Linux

>>:  How to solve the problem that Docker container has no vim command

Recommend

How to embed other web pages in a web page using iframe

How to use iframe: Copy code The code is as follo...

W3C Tutorial (11): W3C DOM Activities

The Document Object Model (DOM) is a platform, a ...

Let's talk about what JavaScript's URL object is

Table of contents Overview Hash Properties Host p...

Summary of the dockerfile-maven-plugin usage guide

Table of contents pom configuration Setting.xml c...

Docker uses Supervisor to manage process operations

A Docker container starts a single process when i...

How to install vim editor in Linux (Ubuntu 18.04)

You can go to the Ubuntu official website to down...

CSS3 analysis of the steps for making Douyin LOGO

"Tik Tok" is also very popular and is s...

Learn MySQL execution plan

Table of contents 1. Introduction to the Implemen...

Detailed installation and use of virtuoso database under Linux system

I've been researching some things about linke...

The magic of tr command in counting the frequency of English words

We are all familiar with the tr command, which ca...

mysql create database, add users, user authorization practical method

1. Create a MySQL database 1. Create database syn...

Detailed process of compiling and installing Storm on Kylin V10 server

1 Introduction Apache Storm is a free, open sourc...