Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

csstree-validator

csstree57kMIT4.0.1

CSS validator built on csstree

css, syntax, validator, checker

readme

NPM Version Build Status Coverage Status

CSSTree Validator

CSS Validator built on CSSTree.

Technically, the package utilizes the capabilities of CSSTree to match CSS syntaxes to various parts of your code and generates a list of errors, if any.

Note: If csstree-validator produces false positives or false negatives, such as unknown properties or invalid values for a property, please report the issue to the CSSTree issue tracker.

Note: CSSTree currently doesn't support selector syntax matching; therefore, csstree-validator doesn't support it either. Support for selector validation will be added once it is available in CSSTree.

Installation

Install the package via npm:

npm install csstree-validator

Usage

You can validate a CSS string or a CSSTree AST:

import { validate } from 'csstree-validator';
// For CommonJS:
// const { validate } = require('csstree-validator');

const filename = 'demo/example.css';
const css = '.class { pading: 10px; border: 1px super red }';

console.log(validate(css, filename));
// Output:
// [
//   SyntaxError [SyntaxReferenceError]: Unknown property `pading` {
//     reference: 'pading',
//     property: 'pading',
//     offset: 9,
//     line: 1,
//     column: 10
//   },
//   SyntaxError [SyntaxMatchError]: Mismatch {
//     message: 'Invalid value for `border` property',
//     rawMessage: 'Mismatch',
//     syntax: '<line-width> || <line-style> || <color>',
//     css: '1px super red',
//     mismatchOffset: 4,
//     mismatchLength: 5,
//     offset: 35,
//     line: 1,
//     column: 36,
//     loc: { source: 'demo/example.css', start: [Object], end: [Object] },
//     property: 'border',
//     details: 'Mismatch\n' +
//       '  syntax: <line-width> || <line-style> || <color>\n' +
//       '   value: 1px super red\n' +
//       '  ------------^'
//   }
// ]

Alternatively, you can use helper functions to validate a file or directory and utilize one of the built-in reporters:

import { validateFile, reporters } from 'csstree-validator';

const result = validateFile('./path/to/style.css');
console.log(reporters.checkstyle(result));

Validation Methods

  • validate(css, filename)
  • validateAtrule(node)
  • validateAtrulePrelude(atrule, prelude, preludeLoc)
  • validateAtruleDescriptor(atrule, descriptor, value, descriptorLoc)
  • validateDeclaration(property, value, valueLoc)
  • validateRule(node)

Helpers

Note: Helpers are not available in browser environments as they rely on Node.js APIs.

All helper functions return an object where the key is the path to a file and the value is an array of errors. The result object is iterable (has Symbol.iterator) and can be used with for...of loops or the spread operator.

Example:

const result = validateFile('path/to/file.css');

for (const [filename, errors] of result) {
  // Process errors
}

Available helper functions:

  • validateString(css, filename)
  • validateDictionary(dictionary)
  • validateFile(filename)
  • validatePath(searchPath, filter)
  • validatePathList(pathList, filter)

Reporters

CSSTree Validator provides several built-in reporters to convert validation results into different formats:

  • console – Human-readable text suitable for console output.
  • json – Converts errors into a unified JSON array of objects:

    type ErrorEntry = {
      name: string; // Filename
      line: number;
      column: number;
      atrule?: string;
      descriptor?: string;
      property?: string;
      message: string;
      details?: any;
    }
  • checkstyleCheckstyle XML report format:

    <?xml version="1.0" encoding="utf-8"?>
    <checkstyle version="4.3">
      <file name="{filename}">
        <error line="{line}" column="{column}" severity="error" message="{message}" source="csstree-validator" />
      </file>
    </checkstyle>
  • gnu – GNU error log format:

    "FILENAME":LINE.COLUMN: error: MESSAGE
    "FILENAME":START_LINE.COLUMN-END_LINE.COLUMN: error: MESSAGE

Example usage:

import { validate, reporters } from 'csstree-validator';

const css = '.class { padding: 10px; color: red; }';
const result = validate(css, 'example.css');

console.log(reporters.json(result));
// Output:
// [
//   { "name": 'example.css', ... },
//   { "name": 'example.css', ... },
//   ...
// ]

Browser Usage

CSSTree Validator can be used in browser environments using the available bundles:

  • IIFE Bundle (dist/csstree-validator.js) – Minified IIFE with csstreeValidator as a global variable.

    <script src="node_modules/csstree-validator/dist/csstree-validator.js"></script>
    <script>
      const errors = csstreeValidator.validate('.some { css: source }');
    </script>
  • ES Module (dist/csstree-validator.esm.js) – Minified ES module.

    <script type="module">
      import { validate } from 'csstree-validator/dist/csstree-validator.esm.js';
    
      const errors = validate('.some { css: source }');
    </script>

You can also use a CDN service like unpkg or jsDelivr. By default, the ESM version is exposed for short paths. For the IIFE version, specify the full path to the bundle:

<!-- ESM -->
<script type="module">
  import * as csstreeValidator from 'https://cdn.jsdelivr.net/npm/csstree-validator';
  // or
  import * as csstreeValidator from 'https://unpkg.com/csstree-validator';
</script>

<!-- IIFE with csstreeValidator as a global -->
<script src="https://cdn.jsdelivr.net/npm/csstree-validator/dist/csstree-validator.js"></script>
<!-- or -->
<script src="https://unpkg.com/csstree-validator/dist/csstree-validator.js"></script>

Note: Helpers are not available in the browser version.

Command-Line Interface (CLI)

Install globally via npm:

npm install -g csstree-validator

Run the validator on a CSS file:

csstree-validator /path/to/style.css

Display help:

csstree-validator -h
Usage:

    csstree-validator [fileOrDir] [options]

Options:

    -h, --help                     Output usage information
    -r, --reporter <nameOrFile>    Output formatter: console (default), checkstyle, json, gnu
                                   or <path to a module>
    -v, --version                  Output version

Custom Reporters

In addition to the built-in reporters, you can specify a custom reporter by providing the path to a module or package. The module should export a single function that takes the validation result object and returns a string:

export default function(result) {
  let output = '';

  for (const [filename, errors] of result) {
    // Generate custom output
  }

  return output;
}

// For CommonJS:
// module.exports = function(result) { ... }

The reporter option accepts:

  • ESM Module – Full path to a file with a .js extension.
  • CommonJS Module – Full path to a file with a .cjs extension.
  • ESM Package – Package name or full path to a module within the package.
  • CommonJS Package – Package name or path to a module within the package.
  • Dual Package – Package name or full path to a module within the package.

The resolution algorithm checks the reporter value in the following order:

  1. If it's a path to a file (relative to process.cwd()), use it as a module.
  2. If it's a path to a package module (relative to process.cwd()), use the package's module.
  3. Otherwise, the value should be the name of one of the predefined reporters, or an error will be raised.

Integrations

Plugins that use csstree-validator:

License

MIT

changelog

4.0.1 (October 11, 2024)

  • Fixed location properties on validation errors; all errors (excluding parse errors) now include offset, start, end, and loc properties

4.0.0 (October 10, 2024)

  • Bumped csstree to ^3.0.0
  • Added default reporters into bundle entry points
  • Fixed the resolution of a path to a reporter by employing enhanced-resolve, which now considers the exports field in package.json
  • Fixed package.json for bundling for browser environments

3.0.0 (December 13, 2021)

  • Added custom reporters support in CLI, e.g. csstree-validator --reporter path/to/reporter.js or csstree-validator --reporter reporter-package
  • Added Symbol.iterator for validateString(), validateDictionary(), validateFile(), validatePathList() and validatePath() result value, i.e. it now can be used with for ... of for example for (const [filename, errors] of result) ...
  • Bumped csstree to 2.0
  • Package
    • Changed supported versions of Node.js to ^12.20.0, ^14.13.0 and >=15.0.0
    • Converted to ES modules. However, CommonJS is supported as well (dual module)
    • Added bundle dist/csstree-validator.esm.js as ES module

2.0.1 (March 31, 2021)

  • Fixed wrong require() in CLI that causes to crash
  • Bumped csstree to 1.1.3 to fix the issue with parsing that causes to a failure on a value with function/brackets and !important (#18)

2.0.0 (November 18, 2020)

  • Droped support for Nodejs < 8
  • Bumped csstree to 1.1.1
  • CLI exits with code 1 and outputs messages to stderr when errors (#12)
  • Added built version for browsers: dist/csstree-validator.js (#11)
  • Added at-rule validation for name, prelude and descriptor
  • Added validateAtrule, validateAtrulePrelude, validateAtruleDescriptor, validateRule and validateDeclaration methods

1.6.0 (October 27, 2020)

  • Bumped csstree to 1.0.0

1.5.1 (October 7, 2019)

1.5.0 (July 11, 2019)

1.4.0 (May 30, 2018)

1.3.1 (February 19, 2018)

  • Updated csstree to 1.0.0-alpha.28

1.3.0 (November 12, 2017)

  • Added gnu reporter (@sideshowbarker, #8)
  • Updated csstree to 1.0.0-alpha.26

1.2.1 (September 14, 2017)

  • Updated csstree to 1.0.0-alpha24 (minor bug fixes)

1.2.0 (September 4, 2017)

  • Updated csstree to 1.0.0-alpha21
  • Use tolerant mode to parse a CSS. Since now a single parse error doesn't prevent validation of a whole CSS.

1.1.0 (August 28, 2017)

  • Updated csstree to 1.0.0-alpha20
  • Changed validate function to always contain a list of errors (no single error on parse error)
  • Added validateDictionary() that validate a dictionary, where key is a filename and value is a CSS as string
  • Changed validateFile(), validatePath() and validatePathList() to handle possible file system exceptions (such errors will be stored as regular errors)
  • Added second argument for validatePath() and validatePathList() to rule which file should be validated. Functions validate files with .css extension only, when second parameter is not passed.
  • Fixed minor issues in reporters output

1.0.8 (January 19, 2017)

  • Added loc to mismatch errors when possible
  • Fixed wrong source in node loc
  • Updated csstree to 1.0.0-alpha13

1.0.7 (January 19, 2017)

  • Updated csstree to 1.0.0-alpha12

1.0.6 (December 23, 2016)

  • Updated csstree to 1.0.0-alpha9

1.0.5 (November 11, 2016)

  • Updated csstree to 1.0.0-alpha8

1.0.4 (October 8, 2016)

  • Updated csstree to 1.0.0-alpha7

1.0.3 (September 23, 2016)

  • Updated csstree to 1.0.0-alpha6 (it was not updated by mistake)

1.0.2 (September 23, 2016)

  • Updated csstree to 1.0.0-alpha6
  • Use syntax validation error line and column when possible to more accurately indicate problem location
  • Improved message output for default reporter
  • Fixed CSS parse error output (or any other exception during validate)

1.0.0 (September 17, 2016)

  • Initial implementation