NPM clean-css Package
Usage
Installation
npm install clean-css
Basic Usage
const cleanCSS = require('clean-css');
// Minify a string of CSS
const result = cleanCSS.minify("body { color: red; }");
// Options
const options = {
level: 2, // Minification level (0-2)
returnPromises: false, // Return a Promise instead of a callback
};
// Minify a file
cleanCSS.minify(['input.css', 'another-input.css'], 'output.css', options);
// Minify multiple files into a single file
cleanCSS.minify(['input1.css', 'input2.css'], 'output.css', options);
// Minify a directory of files
cleanCSS.processFiles('input-directory', 'output-directory', options);
Implementation Guide
Configuration Options
| Option | Description | Default |
|—|—|—|
| level
| Minification level (0-2) | 1 |
| returnPromises
| Return a Promise instead of a callback | false |
Best Practices
- Choose the appropriate minification level: Level 0 is the fastest but least effective, while level 2 is the slowest but most effective.
- Enable compression: The
compress
option can be used to further reduce the output size of your CSS. - Minify multiple files together: This can improve performance by reducing the number of HTTP requests required to load your CSS.
- Use a CSS preprocessor: CSS preprocessors like Sass and Less can help you write more maintainable and reusable CSS.
Examples
Minify a string of CSS
const cleanCSS = require('clean-css');
const result = cleanCSS.minify("body { color: red; }");
console.log(result.styles); // Output: "body{color:red}"
Minify a file
const cleanCSS = require('clean-css');
cleanCSS.minify('input.css', 'output.css', { level: 2 });
Minify multiple files into a single file
const cleanCSS = require('clean-css');
cleanCSS.minify(['input1.css', 'input2.css'], 'output.css', { level: 2 });
Minify a directory of files
const cleanCSS = require('clean-css');
cleanCSS.processFiles('input-directory', 'output-directory', { level: 2 });