1.13.0 • Published 1 year ago

@gojek/postcss-customprop-validate v1.13.0

Weekly downloads
-
License
UNLICENSED
Repository
-
Last release
1 year ago

postcss-customprop-validate

PostCSS plugin to scan a CSS file and validate the CSS Custom Properties' default values.

Use CSS Custom Properties without worrying about the correctness of the default values. This plugin will either auto-correct the CSS file or return an array of all the incorrect ones.

Usage

Install with npm:

npm install @gojek/postcss-customprop-validate --save-dev

or with yarn:

yarn add @gojek/postcss-customprop-validate --dev

PostCSS

Add PostCSS to your build tool:

npm install postcss --save-dev

Use postcss-customprop-validate as a plugin:

import postcss from 'postcss'
import validate from '@gojek/postcss-customprop-validate'

postcss([
  validate(/* options */)
])

Rollup

Add Rollup Plugin PostCSS to your build tool:

npm install rollup-plugin-postcss --save-dev

Use postcss-customprop-validate in your rollup.config.js:

import postcss from 'rollup-plugin-postcss'
import validate from '@gojek/postcss-customprop-validate'

export default {
  plugins: [
    postcss({
      plugins: [
        validate(/* options */)
      ]
    })
  ]
}

List of options

OptionRequiredDescriptionDefault
variablestrueJSON containing the custom properties with their default values. The plugin will throw an error if not passedN.A.
writefalseRewrites the CSS file with correct valuesfalse
callbackfalseCalls callback with an array of incorrect custom properties after the plugin runs.() => {}

Examples

import postcss from "postcss"
import validate from "@gojek/postcss-customprop-validate"

/** CSS with incorrect default values of custom properties */
const css2 = `.Danger {
  color: var(--color-red, red);
  border: var(--custom-border, var(--border-radius, 8px) solid var(--color-red, hsla(292, 56%, 33%, 1)));
}`

/** CSS custom properties JSON to validate values from */
const variables = {
  "--border-radius": "4px",
  "--color-red": "hsla(292, 56%, 33%, 1)",
  "--custom-border":
    "var(--border-radius, 4px) solid var(--color-red, hsla(292, 56%, 33%, 1))"
}

const logValues = arr => console.log(arr)

const process = await postcss([
  validate({ write: false, variables, callback: logValues })
]).process(css)

postcss-customprop-validate will read the CSS and log the result as:

[
  {
    path: { absolute path }, // the absolute path of the CSS file
    line: 2,
    key: '--color-red',
    current: 'red',
    expected: 'hsla(292, 56%, 33%, 1)'
  },
  {
    path: { absolute path }, // the absolute path of the CSS file
    line: 3,
    key: '--custom-border',
    current: 'var(--border-radius, 8px) solid var(--color-red, hsla(292, 56%, 33%, 1))',
    expected: 'var(--border-radius, 4px) solid var(--color-red, hsla(292, 56%, 33%, 1))'
  },
  {
    path: { absolute path }, // the absolute path of the CSS file
    line: 3,
    key: '--border-radius',
    current: '8px',
    expected: '4px'
  }
]