PostCSS JavaScript Functions

4.0.2 · active · verified Sun Apr 19

postcss-functions is a PostCSS plugin that allows developers to expose JavaScript functions for direct invocation within CSS files during the build process. It enables dynamic value generation, complex calculations, and programmatic transformations of CSS properties, extending the capabilities of standard CSS. The current stable version is 4.0.2, maintaining compatibility with PostCSS v8.x. While release cadence isn't strictly defined, major version updates (like 4.0.0) indicate significant changes and active maintenance. Its key differentiator is providing a clean bridge between JavaScript logic and CSS styling without relying on preprocessors, allowing for highly customized and reusable CSS utility functions defined in JavaScript.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic setup, defining custom JavaScript functions, and applying them within CSS using postcss-functions.

import fs from 'fs';
import postcss from 'postcss';
import functions from 'postcss-functions';

const inputCss = `
body {
  /* Example using a custom JS function */
  background-color: myCustomColor('darken', 'blue', 0.2);
}
.foo {
  color: darken(red, 0.1);
}
`;

// Define custom JavaScript functions to be exposed to PostCSS
const customFunctions = {
  myCustomColor: (mode, color, amount) => {
    // A more complex example, could involve external libraries
    if (mode === 'darken') {
      // Simplified darkening logic for demonstration
      return `rgba(0, 0, ${Math.floor(255 * (1 - parseFloat(amount)))}, 1)`;
    }
    return color;
  },
  darken: (value, frac) => {
    // Basic example of a function, similar to the README
    const darkenFactor = 1 - parseFloat(frac);
    // In a real scenario, use a color manipulation library
    // For demo, just return a string
    return `rgba(0, 0, ${Math.floor(255 * darkenFactor)}, 1)`;
  }
};

postcss()
  .use(functions({ functions: customFunctions }))
  .process(inputCss, { from: undefined })
  .then((result) => {
    console.log('Processed CSS:\n', result.css);
  })
  .catch((error) => {
    console.error('PostCSS processing failed:', error);
  });

view raw JSON →