Home

Awesome

style-vendorizer

Tiny CSS vendor prefixer and property alias mapper for runtime styling solutions.

npm npm bundle size GitHub Workflow Status (branch) Contributor Covenant

Usage

Install the library with a package manager, e.g. npm:

npm install style-vendorizer

After that, import transformer functions on demand. A recommended starting point is shown below:

import {
  cssPropertyAlias,
  cssPropertyPrefixFlags,
  cssValuePrefixFlags,
} from "style-vendorizer";

function styleDeclaration(property, value) {
  let cssText = "";

  /* Resolve aliases, e.g. `gap` -> `grid-gap` */
  const propertyAlias = cssPropertyAlias(property);
  if (propertyAlias) cssText += `${propertyAlias}:${value};`;

  /* Prefix properties, e.g. `backdrop-filter` -> `-webkit-backdrop-filter` */
  const propertyFlags = cssPropertyPrefixFlags(property);
  if (propertyFlags & 0b001) cssText += `-webkit-${property}:${value};`;
  if (propertyFlags & 0b010) cssText += `-moz-${property}:${value};`;
  if (propertyFlags & 0b100) cssText += `-ms-${property}:${value};`;

  /* Prefix values, e.g. `position: "sticky"` -> `position: "-webkit-sticky"` */
  /* Notice that flags don't overlap and property prefixing isn't needed here */
  const valueFlags = cssValuePrefixFlags(property, value);
  if (valueFlags & 0b001) cssText += `${property}:-webkit-${value};`;
  else if (valueFlags & 0b010) cssText += `${property}:-moz-${value};`;
  else if (valueFlags & 0b100) cssText += `${property}:-ms-${value};`;

  /* Include the standardized declaration last */
  /* https://css-tricks.com/ordering-css3-properties/ */
  cssText += `${property}:${value};`;

  return cssText;
}

Prefix flags may be defined in TypeScript without any overhead as follows:

<!-- prettier-ignore-start -->
const enum CSSPrefixFlags {
  "-webkit-" = 1 << 0, // 0b001
     "-moz-" = 1 << 1, // 0b010
      "-ms-" = 1 << 2, // 0b100
}

/* Magic numbers from the previous snippet should be replaced like below: */
if (flags & CSSPrefixFlags["-webkit-"]) cssText += "...";
if (flags & CSSPrefixFlags["-moz-"]) cssText += "...";
if (flags & CSSPrefixFlags["-ms-"]) cssText += "...";
<!-- prettier-ignore-end -->

Browser Support

Every browser in the default Browserslist configuration is supported and tested against:

Quirks

Acknowledgements

This project was heavily inspired by tiny-css-prefixer. Test vectors are obtained from @mdn/browser-compat-data.