Welcome to Clean-CSS
Clean-CSS is a powerful and fast optimizer for CSS that’s used by thousands of web developers to reduce the size of their CSS files, ensuring faster load times and better page performance. Here, we’ll explore various APIs offered by Clean-CSS, complete with practical code snippets for better understanding.
Getting Started with Clean-CSS
First, let’s start by installing Clean-CSS via npm:
npm install clean-css
Basic Usage
Here’s a basic usage of Clean-CSS to minify a CSS string:
const CleanCSS = require('clean-css');
const input = 'a{font-weight:bold;}';
const output = new CleanCSS().minify(input).styles;
console.log(output); // Output: 'a{font-weight:700}'
Minifying Files
Clean-CSS can also be used to minify CSS files directly:
const CleanCSS = require('clean-css');
const fs = require('fs');
const input = fs.readFileSync('path/to/your.css', 'utf8');
const output = new CleanCSS().minify(input).styles;
fs.writeFileSync('path/to/your.min.css', output);
Using Options
Clean-CSS supports a wide range of options that allow you to customize the minification process:
const CleanCSS = require('clean-css');
const input = 'a{font-weight:bold;}';
const options = {
level: {
1: {
all: true,
specialComments: 0
},
2: {
restructureRules: true
}
}
};
const output = new CleanCSS(options).minify(input);
console.log(output.styles); // Output: 'a{font-weight:700}'
Inlining and Sourcing
Clean-CSS allows inlining of @import
rules and rebase URLs:
const CleanCSS = require('clean-css');
const input = 'body{color:red;}@import(url("additional.css"));';
const options = {
inline: ['local'],
rebase: true
};
new CleanCSS(options).minify(input, (error, output) => {
console.log(output.styles);
});
Integrating Clean-CSS into Your App
Here’s how you can integrate Clean-CSS into a simple Node.js web application:
const express = require('express');
const CleanCSS = require('clean-css');
const fs = require('fs');
const app = express();
app.get('/minify-css', (req, res) => {
const input = fs.readFileSync('path/to/styles.css', 'utf8');
const output = new CleanCSS().minify(input).styles;
res.send(output);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Conclusion
Clean-CSS is an indispensable tool for web developers looking to optimize their CSS for better performance. By leveraging its versatile API, you can easily integrate CSS minification into your workflow, ensuring leaner and faster-loading web pages.
Hash: fddb40b7803b72e44ec7b71e56e49a2842f0d530a9082f6b6f21786f8482f99d