npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

postcss-theme-manager

v0.0.15

Published

PostCSS plugin for generate multiple themes CSS files

Downloads

9

Readme

Will create class overrides for legacy browsers and use CSS variables for modern browsers.

  • Supports light and dark color schemes

  • Create component level themes

  • Supports scoping CSS Variable names to mitigate conflicts

  • Themes can extend other themes

Setup

First install the dependencies.

npm install --save-dev postcss postcss-theme-manager

Usage

const config = {
  default: {
    color: 'white',
  },
  other: {
    color: 'black',
  },
};

or for per theme light and dark modes:

const config = {
  default: {
    light: {
      color: 'white',
    },
    dark: {
      color: 'black',
    },
  },
  // Can still just have one level which defaults to light
  other: {
    color: 'purple',
  },
  more: {
    light: {
      color: 'red',
    },
    dark: {
      color: 'blue',
    },
  },
};
import postcss from 'postcss';
import themeManager, { type PostcssThemeOptions } from 'postcss-theme-manager';

const options: PostcssThemeOptions = {
  config: {
    default: {
      light: {
        color: 'white',
      },
      dark: {
        color: 'black',
      },
    },
  },
};

postcss([themeManager(options)]);

See PostCSS docs for examples for your environment.

Using Theme Variables

Input:

.foo {
  color: @theme color;
  border: @theme border-width solid @theme color;
}

/* OR */

.foo {
  color: theme('color');
  border: theme('border-width') solid theme('color');
}

Output:

.foo {
  color: white;
  border: 1px solid white;
}
.other .foo {
  color: black;
  border: 10px solid black;
}

Theming with Objects

You can even keep theme values in deeply nested objects.

Input:

const config = {
  default: {
    colors: {
      primary: 'white',
    },
  },
  other: {
    colors: {
      primary: 'black',
    },
  },
};
.foo {
  color: @theme colors.primary;
}

Output:

.foo {
  color: white;
}

.other .foo {
  color: black;
}

Component themes

Define a component level theme in either commonjs or typescript. A file names themes.(js|ts) must be co-located with the themeable CSS file.

themes.js:

module.exports = (theme) => ({
  default: {
    border: `1px solid ${theme.default.color}`
  }
  other: {
    border: `1px solid ${theme.other.color}`
  }
});

themes.ts:

import { Theme } from '@your/themes';

const CardTheme = (theme: Theme): Theme => ({
  default: {
    border: '1px solid red',
  },
  other: {
    border: `1px solid ${theme.other.color}`,
  },
});

export default CardTheme;

or provide a function to locate the theme function

Theme Resolution

By default this plugin will looks for a sibling theme.js or theme.ts. You can customize the lookup behavior by supplying your own theme resolution function.

postcss([
  require('postcss-theme-manager')({
    config,
    resolveTheme: (cssFileName) => {
      // return a function like the ones above
    },
  }),
]);

Now you can use @theme border in your CSS file.

Theme Extension

Any theme can extend another theme. This is useful when you are defining a child theme that customizes some stuff but in general adopts most of the styling of another theme.

Config:

const config = {
  default: {
    color: 'white',
    background: 'black',
  },
  myTheme: {
    color: 'purple',
    background: 'green',
  },
  myChildTheme: {
    extends: 'myTheme',
    background: 'red',
  },
};

Input:

.test {
  color: @theme color;
  background: @theme background;
}

Output:

.test {
  color: var(--color, white);
  background: var(--background, black);
}

.myTheme {
  --color: purple;
  --background: green;
}

.myChildTheme {
  --color: purple;
  --background: red;
}

Theming Root class (LEGACY ONLY)

Only needed when targeting legacy environments that do not support CSS Variables.

Input:

:theme-root(.foo) {
  border: 1px solid @theme color;
}

or by nesting

Input:

:theme-root {
  &.foo {
    border: 1px solid @theme color;
  }
}

Output:

.foo {
  border: 1px solid white;
}
.foo.other {
  border: 1px solid black;
}

Options

modules

This plugin also support scoping your CSS Variable names in a very similar way to CSS Modules. This option should be used when targeting browsers with css variables to avoid name collisions.

You can use any of the tokens listed here to create a scoped name. The token [local] is also available which is the name of the original theme variable.

postcss([
  require('postcss-theme-manager')({
    config,
    modules: '[folder]-[name]-[local]',
  }),
]);

Another option is to use the default function for scoping variable names.

To use the default function:

postcss([
  require('postcss-theme-manager')({
    config,
    modules: 'default',
  }),
]);

The default function combines the filepath, name and hashed css into a single string and uses it as a variable name.

const defaultLocalizeFunction = (
  name: string,
  filePath: string,
  css: string
) => {
  const hash = crypto.createHash('md5').update(css).digest('hex').slice(0, 6);
  return `${filePath || 'default'}-${name}-${hash}`;
};

You can also supply your own function for scoping variable names, again following the API from CSS Modules. If PostCSS does not have a path for the file both the path and css will return an empty string.

postcss([
  require('postcss-theme-manager')({
    config,
    modules: (name: string, filePath: string, css: string) => {
      const hash = crypto
        .createHash('sha1')
        .update(css)
        .digest('hex')
        .slice(0, 3);
      return `${filePath}-${name}-${hash}`;
    },
  }),
]);

defaultTheme

An optional parameter to change the name of the default theme (where no extra classes are added to the selector). It defaults to default, and also corresponds to the only required key in your theme.ts files.

lightClass + darkClass

Classes to apply to color scheme overrides.

postcss([
  require('postcss-theme-manager')({
    config,
    lightClass: '.light-theme',
    darkClass: '.dark-theme',
  }),
]);

forceEmptyThemeSelectors - only legacy

By default this plugin will not produce class names for theme that have no component level configuration if there are no styles. (ex: you have 3 themes but your component only uses 1, then only 1 extra set of classnames is produced).

You can use the forceEmptyThemeSelectors to force these empty classes to be added. If you use this option you should also use some form of css minification that can get rid of the empty classes. If you don't your CSS will be bloated.

This feature is useful if your are converting your css-modules to typescript and need the generated typescript file to include all of the possible themes.

postcss([
  require('postcss-theme-manager')({ config, forceEmptyThemeSelectors: true }),
]);

forceSingleTheme

This is a niche option which only inserts a single theme. At first glance, this may seem strange because this plugin primarily allows you to support many themes in a single CSS file. This option helps if you want to generate many CSS files, each with their own theme. You'll run PostCSS multiple times, switching the single theme. In practice, we use this to generate extra CSS files for teams that only need a single theme. The main CSS file still has all of them, but teams can optionally use the one that only has the theme they need.

It is still recommended to set defaultTheme with this option, as any missing variables will be merged with the default.

Config:

const config = {
  default: {
    light: {
      color: 'purple',
    },
    dark: {
      color: 'black',
    },
  },
  chair: {
    light: {
      color: 'beige',
    },
    dark: {
      color: 'dark-purple',
    },
  },
};

postcss([
  require('postcss-theme-manager')({
    config,
    defaultTheme: 'default',
    forceSingleTheme: 'chair',
  }),
]);

Input:

.test {
  color: @theme color;
}

Output:

.test {
  color: var(--color);
}

:root {
  --color: beige;
}

.dark {
  --color: dark-purple;
}

As you can see in the above example, only one theme will be generated using this option.

optimizeSingleTheme

This option should only be used in conjunction with forceSingleTheme. By default forceSingleTheme will always add CSS variables, since many users still want to be able to modify and override them. However, if you are not going to be modifying them, we can optimize the single theme further by removing variables when possible. If only a light theme is specified, this config option will just do in-place replacement of the theme variables.

Config:

const config = {
  default: {
    color: 'purple',
  },
  chair: {
    color: 'beige',
  },
};

postcss([
  require('postcss-theme-manager')({
    config,
    defaultTheme: 'default',
    forceSingleTheme: 'chair',
    optimizeSingleTheme: true,
  }),
]);

Input:

.test {
  color: @theme color;
}

Output:

.test {
  color: beige;
}

Debug

This package uses the npm package debug to log errors while it's running.

Simply set the DEBUG environment variable to postcss-theme-manager.

DEBUG=postcss-theme-manager postcss input.css -o output.css