Skip to content
This repository was archived by the owner on Apr 5, 2022. It is now read-only.

Repository files navigation

Babel CSS Inline Plugin

DEPRECATED!

If possible use your bundler to inline CSS. This plugin was written before Microbundle implemented that feature. Webpack and Microbundle both support inlining CSS now.


codecovBuild Statusnpm version

This plugin parses css with PostCSS and inline it into JavaScript.

Example

CSS File
div {
color:#333;
display: flex;
}
JS File
importstylesfrom"./styles.css";
JavaScript Output
conststyles="div{color:#333;display:flex;display:-webkit-flex}";

Why?

This plugin is created to inline CSS into WebComponents with a ShadowRoot.

importstylesfrom"./my-component.css";classMyComponentextendsHTMLElement{protectedreadonly_root: ShadowRoot;constructor(){super();this._root=this.attachShadow({mode: "closed"});}connectedCallback(){conststyle=document.createElement("style");style.textContent=styles;this._root.appendChild(style);}}

Currently autoprefixer and cssnano are enabled. To configure the browsers to support simply add a browserlist property to the `package.

Usage

Install the plugin:

npm install --save-dev @owja/babel-css-inline-plugin

Add the plugin to the Babel configuration:

babel.config.js

module.exports={plugins: ['module:@owja/babel-css-inline-plugin'],};

With TypeScript you have to add a definition file:

src/types/css.d.ts

declare module "*.css"{constcontent: string;exportdefaultcontent;}

Now you can import CSS files:

importstylesfrom"./my-styles.css";

which compiles to

conststyles="<css styles>";

Notice

The plugin uses PostCSS CLI which is slow. The reason is that Babel does not support async plugins yet. This might change in the future. A other workaround could be to implement a server/client to sync PostCSS.

This plugin is marked as alpha but it should stay backwards compatible.

It is possible that we will add some features in the future:

  • CSS Modules
  • Configurable file extension, to make it possible to only inline specific files

Development

Clone this repository and run npm install.

Tests

npm test

Build

npm run build

License

MIT

Copyright © 2020 Hauke Broer

About

🎁 Babel plugin to parses CSS with PostCSS and injecting into JavaScript

Topics

Resources

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages