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

Solution to the data asymmetry problem between MySQL and Elasticsearch

Solution to the data asymmetry problem between My...

Tutorial on installing Pycharm and Ipython on Ubuntu 16.04/18.04

Under Ubuntu 18.04 1. sudo apt install python ins...

Tutorial on Migrating Projects from MYSQL to MARIADB

Prepare the database (MySQL). If you already have...

JavaScript to implement dynamic digital clock

This article shares the specific code for impleme...

Linux system prohibits remote login command of root account

ps: Here is how to disable remote login of root a...

Design theory: people-oriented green design

Reflections on the two viewpoints of “people-orie...

Implementation of importing and exporting vue-element-admin projects

vue-element-admin import component encapsulation ...

mysql5.6.8 source code installation process

Kernel: [root@opop ~]# cat /etc/centos-release Ce...

Commonplace talk about MySQL event scheduler (must read)

Overview MySQL also has its own event scheduler, ...

Vue practice of preventing multiple clicks

Generally, click events will be divided into diff...

CSS Reset style reset implementation example

Introduction: All browsers come with default styl...

Examples of preview functions for various types of files in vue3

Table of contents Preface 1. Preview of office do...

Detailed explanation of the calculation method of flex-grow and flex-shrink in flex layout

Flex(彈性布局) in CSS can flexibly control the layout...