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 start a Java program in docker

Create a simple Spring boot web project Use the i...

Vue3+script setup+ts+Vite+Volar project

Table of contents Create a vue + ts project using...

Summary of several implementations of returning to the top in HTML pages

Recently, I need to make a back-to-top button whe...

Detailed tutorial on VMware installation of Linux CentOS 7.7 system

How to install Linux CentOS 7.7 system in Vmware,...

How to debug loader plugin in webpack project

Recently, when I was learning how to use webpack,...

Vue scroll down to load more data scroll case detailed explanation

vue-infinite-scroll Install npm install vue-infin...

CentOS 7 switching boot kernel and switching boot mode explanation

centos7 switch boot kernel Note: If necessary, it...

How to create users and manage permissions in MySQL

1. How to create a user and password 1. Enter the...

How to encapsulate the table component of Vue Element

When encapsulating Vue components, I will still u...

In-depth understanding of javascript prototype and prototype chain

Table of contents 1. What is a prototype? 2. Prot...

How to install Docker CE on Ubuntu 18.04 (Community Edition)

Uninstall old versions If you have installed an o...

Introduction to JavaScript array deduplication and flattening functions

Table of contents 1. Array flattening (also known...

Let's talk about the difference between containers and images in Docker

What is a mirror? An image can be seen as a file ...