Home

Awesome

csstag

Build Status

Use CSS Modules as tagged templates in a browser and Node.js. Example:

import css from 'csstag';
const styles = css`
  .root {
    color: red;
  }
`;
<div class={styles.root} />;

Demo: https://sgtpep.github.io/csstag/demo/.

Benefits over other CSS-in-JS libraries

Installation

Using npm

npm install csstag

Using yarn

yarn add csstag

Importing

From Node.js

const { css } = require('csstag');

Or from .mjs:

import css from 'csstag';

From a bundler (webpack, etc.)

import css from 'csstag';

From a browser

If you don't use a bundler (webpack, etc.) but prefer native ES6 modules instead (<script type="module"></script>):

import css from './node_modules/csstag/index.min.js';

Or use unpkg CDN:

import css from 'https://unpkg.com/csstag';

Usage

Once imported you can declare a CSS module as a tagged template using the tag function css:

import css, { appendStyles } from 'csstag';

const styles = css`
  .foo {
    color: red;
  }
  .bar {
    color: blue;
  }
`;

It returns an object with all exported class names in it:

console.log(styles);
{ foo: 'csstag__foo___LTk0O', bar: 'csstag__bar___LTk0O' }

The module csstag contains the array of compiled styles called styles, which is populated with a new item every time css tag function is being called, and now contains:

[
  `.csstag__foo___LTk0O {
    color: red;
  }
  .csstag__bar___LTk0O {
    color: blue;
  }`,
];

You may want to append all newly added items from that array as a stylesheet as <style> in your document's <head> using the function appendStyles imported earlier (in React-like projects it makes sense to call it together with render() in your entry point):

appendStyles();

If you're using Prettier, it will format the CSS code inside css tag function.

csstag itself comes as a bundle containing some heavy-weight packages like PostCSS and has a size of ~100K minimized. To exclude it from production code and leave only compiled styles you might use a Babel plugin babel-plugin-csstag.

API

If you don't like storing a list of built stylesheets in csstag module's styles array, or you're dealing, for instance, with multiple applications at once, you may create new functions bound to any other array using .bind():

import csstag, { appendStyles } from 'csstag';

const styles = [];
const css = csstag.bind(styles);
css`
  .root {
    color: red;
  }
`;
appendStyles.bind(styles)();

Options

To pass options pass an object with them as a second argument of .bind():

import csstag from 'csstag';

const css = csstag.bind(null, { prefix: 'myapp' });