postcss-functions-lite

PostCSS plugin for exposing JavaScript functions.

Usage no npm install needed!

<script type="module">
  import postcssFunctionsLite from 'https://cdn.skypack.dev/postcss-functions-lite';
</script>

README

Postcss-functions-lite

PostCSS plugin for exposing JavaScript functions. This is a lite alternative which doesn't include globbing or have promises built in.

Inspired by postcss functions by Andy Jansson.

Key differences between lite and functions

Lite is a bare minimal alternative of postcss functions

  • Globbing is not built in.
  • Promises are not built in.

Installation

npm install --save-dev postcss-functions-lite

Requirements

  • Postcss 8

Usage

const fs = require('fs')
const postcss = require('postcss')
const postcssFunctions = require('postcss-functions-lite')

const options = {
  // options
}

const css = fs.readFileSync('input.css', 'utf8')

postcss()
  .use(postcssFunctions(options))
  .process(css)
  .then(result => {
    const output = result.css
  })

Example of a function call:

body {
  prop: foobar()
}

Options

functions

Type: Object

An object containing functions. The function name will correspond with the object key.

Example:

const color = require('css-color-converter')
const postcssFunctions = require('postcss-functions-lite')

return postcssFunctions({
  functions: {
    darken: (value, frac) =>  {
      const darken = 1 - parseFloat(frac)
      const rgba = color(value).toRgbaArray()
      const r = rgba[0] * darken
      const g = rgba[1] * darken
      const b = rgba[2] * darken
      return color([r,g,b]).toHexString()
    }
  }
})
.foo {
  /* make 10% darker */
  color: darken(blue, 0.1)
}

Globbing

As mentioned above lite doesn't include globbing. If you require globbing then it is recommended to switch to functions or alternatively build a basic glob.

Example:

const path require('path')
const glob = require('glob')
const postcssFunctions = require('postcss-functions-lite')
let globFunctions = {}

// ...
glob.sync('**/*.js').forEach(file => {
  const name = path.basename(file, path.extname(file))
  globFunctions[name] = require(path.basename(file, path.extname(file)))
})
// ...

return postcssFunctions({
  functions: {
    doSomething: (value) =>  {
      // do something
    },
    ...globFunctions
  }
})