CSS Minifier and Utility Library

0.12.3 · abandoned · verified Sun Apr 19

Crass is a JavaScript utility library designed for CSS minification, pretty-printing, and general manipulation. Unlike many other CSS minifiers that operate on string-based transformations, Crass constructs a full parse tree of the CSS, enabling deeper and more accurate optimizations, particularly for gzip compression, and consistent pretty-printing. It supports CSS3 and CSS4 features, with options to strip obsolete tags based on browser versions and convert colors to their smallest forms. The current stable version is 0.12.3, last published in February 2018. The project is no longer actively maintained, making it an abandoned library. Its primary differentiator is its parse-tree approach, which, while slower, allows for advanced optimizations not possible with string-manipulation tools.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing, basic and advanced optimization, minification, and pretty-printing of CSS using the Crass API.

const crass = require('crass');

// Example CSS with various features for demonstration
const cssInput = `
  @charset "UTF-8";
  /* A comment */
  .container {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px 20px 5px;
    padding: 1em;
    color: #FF0000; /* Red */
    font-size: 16px;
    border: 1px solid #ccc;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  @media (max-width: 600px) {
    .container {
      flex-direction: column;
      margin: 5px;
    }
  }
  a:hover {
    text-decoration: underline;
  }
  /*
    Crass can also perform optimizations like
    shorthand conversions and color compression.
  */
  body {
    background: rgb(255, 255, 255);
  }
`;

// Parse the CSS stylesheet into an AST
let parsed = crass.parse(cssInput);
console.log('--- Original Parse Tree (toString output) ---');
console.log(parsed.toString()); // Default toString() output is minified

// Optimize the stylesheet (basic optimization)
parsed = parsed.optimize();
console.log('\n--- Optimized & Minified ---');
console.log(parsed.toString());

// Optimize with advanced optimizations (O1 flag)
// Note: O1 can be more aggressive and might not be suitable for all CSS.
const parsedO1 = crass.parse(cssInput).optimize({ o1: true });
console.log('\n--- Optimized (O1) & Minified ---');
console.log(parsedO1.toString());

// Pretty print the stylesheet for readability
console.log('\n--- Pretty Printed ---');
console.log(parsed.pretty());

// Access AST nodes (example: count rules)
const rules = parsed.node.rules.filter(node => node.type === 'rule');
console.log(`\nFound ${rules.length} CSS rules after parsing and optimizing.`);

view raw JSON →