tooling.report

feature

Source

Can CSS be imported as a JavaScript string?

Person in shorts with blue hair walking left

Introduction

There are a number of circumstances in which it is useful to be able to import a CSS stylesheet from JavaScript. One of the most common use-cases is to load styles for a reusable UI component library, which generally requires that the stylesheet can be imported as a JavaScript string.

In the future, it may be possible to explicitly specify how a non-JavaScript import should be handled using something like Module Attributes.

The Test

In this test, a CSS file is imported by a JavaScript module and its string representation is injected into a <style> element, applying the style rules to the page.

index.js

import css from './styles.css';

// do something with the stylesheet text:
const style = document.createElement('style');
style.textContent = css;
document.head.append(style);

styles.css

html {
  background: green;
}

h1 {
  color: white;
}

The resulting bundle should include a JavaScript string containing the stylesheet from styles.css. The stylesheet string should also be minified (rules deduplicated, whitespace removed, etc) in order to pass this test.

Conclusion

browserify

Browserify can be configured to allow requiring .css files from JavaScript using browserify-css. In cases where the raw CSS is needed, setting autoIjnect to false will return the minified stylesheet as a String.

parcel

Parcel supports this out-of-the box via an import with a special scheme, bundle-text:.

Issues

rollup

There are plugins for postcss such as rollup-plugin-postcss, but it's also reasonably straightforward to create a small plugin that uses postcss directly.

webpack

css-loader processes imported CSS files, which can then be passed through extract-loader to obtain the stylesheet text as a string. Setting the module's type option to "asset/source" will embed this into the bundle.