or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-features.mdbatch-processing.mdcompatibility.mdconstructor-options.mdindex.mdinput-output.mdoptimization-levels.md
tile.json

batch-processing.mddocs/

Batch Processing and Promise Interface

Clean-CSS provides flexible batch processing capabilities for handling multiple CSS files independently, along with Promise-based async workflows for modern JavaScript applications.

Batch Processing

Batch processing allows you to minify multiple CSS files or inputs while keeping their results separate, rather than concatenating them into a single output.

Enabling Batch Mode

const batchMinifier = new CleanCSS({ batch: true });

When batch: true is set in the constructor options, the minify method returns a hash object with individual results for each input.

Batch Result Format

interface BatchResult {
  [filename: string]: MinifyResult;
}

// Where each MinifyResult contains:
interface MinifyResult {
  styles: string;
  errors: string[];
  warnings: string[];
  stats: MinifyStats;
  inlinedStylesheets: string[];
  sourceMap?: object;
}

Batch Processing with Arrays

Process multiple files provided as an array of file paths:

const CleanCSS = require('clean-css');
const batchMinifier = new CleanCSS({ 
  batch: true,
  level: 2 
});

const files = [
  'src/styles/main.css',
  'src/styles/components.css',
  'src/styles/utilities.css'
];

const results = batchMinifier.minify(files);

// Results structure:
// {
//   'src/styles/main.css': { styles: '...', errors: [], ... },
//   'src/styles/components.css': { styles: '...', errors: [], ... },
//   'src/styles/utilities.css': { styles: '...', errors: [], ... }
// }

// Process each result
Object.keys(results).forEach(filename => {
  const result = results[filename];
  console.log(`${filename}: ${result.stats.originalSize} → ${result.stats.minifiedSize} bytes`);
  
  if (result.errors.length > 0) {
    console.error(`Errors in ${filename}:`, result.errors);
  }
});

Batch Processing with Hash Objects

Process multiple files with explicit content using hash objects:

const inputHash = {
  'main.css': {
    styles: `
      body {
        margin: 0;
        font-family: Arial, sans-serif;
      }
    `
  },
  'components.css': {
    styles: `
      .button {
        padding: 10px 20px;
        background-color: #007bff;
        color: white;
      }
    `,
    sourceMap: existingSourceMap  // Optional
  },
  'utilities.css': {
    styles: `
      .text-center { text-align: center; }
      .hidden { display: none; }
    `
  }
};

const results = batchMinifier.minify(inputHash);

// Access individual results
const mainResult = results['main.css'];
const componentResult = results['components.css'];
const utilityResult = results['utilities.css'];

Mixed Array and Hash Processing

Batch processing can handle nested structures:

const mixedInputs = [
  'global.css',  // File path
  {
    'theme.css': { styles: '.theme { background: white; }' },
    'print.css': { styles: '@media print { body { font-size: 12pt; } }' }
  }
];

const results = batchMinifier.minify(mixedInputs);
// Results include both file path and hash object entries

Promise Interface

The Promise interface provides async/await support and better error handling for modern JavaScript applications.

Enabling Promise Mode

const promiseMinifier = new CleanCSS({ 
  returnPromise: true,
  level: 2
});

When returnPromise: true is set, the minify() method returns a Promise instead of calling a callback.

Promise Return Type

minify(input: CleanCSSInput): Promise<MinifyResult>

Note: When Promise mode is enabled, the callback parameter is ignored.

Basic Promise Usage

const CleanCSS = require('clean-css');
const promiseMinifier = new CleanCSS({ 
  returnPromise: true,
  level: 2,
  sourceMap: true
});

const css = `
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
`;

// Using Promises
promiseMinifier.minify(css)
  .then(result => {
    console.log('Minified CSS:', result.styles);
    console.log('Efficiency:', result.stats.efficiency);
    
    if (result.sourceMap) {
      console.log('Source map generated');
    }
    
    return result;
  })
  .catch(errors => {
    console.error('Minification failed:', errors);
  });

Async/Await Usage

async function minifyCSS(cssInput) {
  try {
    const result = await promiseMinifier.minify(cssInput);
    
    if (result.errors.length > 0) {
      console.warn('Minification completed with errors:', result.errors);
    }
    
    return {
      css: result.styles,
      sourceMap: result.sourceMap,
      stats: result.stats
    };
  } catch (errors) {
    throw new Error(`CSS minification failed: ${errors.join(', ')}`);
  }
}

// Usage
try {
  const output = await minifyCSS(inputCSS);
  console.log('Minification successful:', output.stats);
} catch (error) {
  console.error('Error:', error.message);
}

Promise Error Handling

promiseMinifier.minify('@import "nonexistent.css"; body { margin: 0; }')
  .then(result => {
    // Check for non-fatal errors
    if (result.errors.length > 0) {
      console.warn('Non-fatal errors occurred:', result.errors);
    }
    
    // Process successful result
    return processMinifiedCSS(result.styles);
  })
  .catch(errors => {
    // Handle fatal errors that prevented minification
    console.error('Fatal minification errors:', errors);
    return handleMinificationFailure(errors);
  });

Combined Batch and Promise Processing

You can combine batch processing with the Promise interface for powerful async batch operations:

const batchPromiseMinifier = new CleanCSS({ 
  batch: true,
  returnPromise: true,
  level: 2 
});

Async Batch Processing

async function processCSSFiles(fileList) {
  try {
    const results = await batchPromiseMinifier.minify(fileList);
    
    const processedFiles = [];
    const errorFiles = [];
    
    Object.keys(results).forEach(filename => {
      const result = results[filename];
      
      if (result.errors.length > 0) {
        errorFiles.push({
          filename,
          errors: result.errors
        });
      } else {
        processedFiles.push({
          filename,
          originalSize: result.stats.originalSize,
          minifiedSize: result.stats.minifiedSize,
          efficiency: result.stats.efficiency,
          css: result.styles
        });
      }
    });
    
    return {
      successful: processedFiles,
      failed: errorFiles
    };
  } catch (errors) {
    throw new Error(`Batch processing failed: ${errors.join(', ')}`);
  }
}

// Usage
const cssFiles = [
  'styles/main.css',
  'styles/components.css',
  'styles/themes.css'
];

processCSSFiles(cssFiles)
  .then(results => {
    console.log(`Successfully processed ${results.successful.length} files`);
    console.log(`Failed to process ${results.failed.length} files`);
    
    results.successful.forEach(file => {
      console.log(`${file.filename}: ${file.efficiency * 100}% compression`);
    });
    
    results.failed.forEach(file => {
      console.error(`${file.filename}:`, file.errors);
    });
  })
  .catch(error => {
    console.error('Batch processing error:', error.message);
  });

Parallel Processing with Promise.all

For independent file processing, you can use multiple Clean-CSS instances:

async function parallelMinification(files) {
  const minifiers = files.map(() => new CleanCSS({ 
    returnPromise: true,
    level: 2 
  }));
  
  const promises = files.map((file, index) => 
    minifiers[index].minify(file)
      .then(result => ({ file, result, success: true }))
      .catch(errors => ({ file, errors, success: false }))
  );
  
  const results = await Promise.all(promises);
  
  const successful = results.filter(r => r.success);
  const failed = results.filter(r => !r.success);
  
  return { successful, failed };
}

Static Process Method

Clean-CSS also provides a static method for webpack plugin compatibility:

static process(input: CleanCSSInput, opts: object): Promise<{ css: string }>

This method always returns a Promise and is designed for compatibility with optimize-css-assets-webpack-plugin:

const result = await CleanCSS.process(cssInput, {
  level: 2,
  to: '/output/path'  // Special 'to' option for webpack compatibility
});

console.log(result.css); // Minified CSS output

The process method differs from the instance minify method:

  • Always returns a Promise
  • Returns simplified { css: string } format
  • Supports webpack-specific options like to
  • Creates a temporary Clean-CSS instance internally