Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
PurgeCSS is a tool to remove unused CSS. It can be used as part of your development workflow to reduce the size of your CSS files by removing unused selectors.
Basic Usage
This code demonstrates the basic usage of PurgeCSS. It scans HTML files and CSS files to remove unused CSS selectors.
const PurgeCSS = require('purgecss');
const purgeCSSResults = new PurgeCSS().purge({
content: ['**/*.html'],
css: ['**/*.css']
});
console.log(purgeCSSResults);
Using with PostCSS
This code shows how to integrate PurgeCSS with PostCSS. It processes CSS files and removes unused selectors based on the content of HTML files.
const postcss = require('postcss');
const purgecss = require('@fullhuman/postcss-purgecss');
postcss([
purgecss({
content: ['./src/**/*.html']
})
]).process(css, { from: 'src/app.css', to: 'dist/app.css' })
.then(result => {
console.log(result.css);
});
Using with Webpack
This code demonstrates how to use PurgeCSS as a Webpack plugin. It scans the specified paths for content and removes unused CSS selectors during the Webpack build process.
const PurgeCSSPlugin = require('purgecss-webpack-plugin');
const glob = require('glob');
const path = require('path');
module.exports = {
// other webpack config
plugins: [
new PurgeCSSPlugin({
paths: glob.sync(`${path.join(__dirname, 'src')}/**/*`, { nodir: true }),
}),
],
};
UnCSS is a tool that removes unused CSS from your stylesheets. It works similarly to PurgeCSS by scanning your HTML files to determine which CSS selectors are not used. However, UnCSS is generally considered to be less flexible and slower compared to PurgeCSS.
PurifyCSS is another tool for removing unused CSS. It scans your HTML and JavaScript files to find which CSS selectors are used. While it is similar to PurgeCSS, it is not as actively maintained and may lack some of the advanced features and integrations that PurgeCSS offers.
CSSO (CSS Optimizer) is a CSS minifier that also has the capability to remove unused CSS. It is primarily focused on minification and optimization, but it can also be used to remove unused CSS selectors. CSSO is generally faster but may not be as thorough in removing unused CSS as PurgeCSS.
Purgecss is a tool inspired by Purifycss to remove unused css. Originally thought as the v2 of purifycss,
purgecss has for goal to act in a similar way while correcting the known ploblems of purifycss. If you want
to know more about the differences between purifycss and purgecss, go to the section Differences with.
When you are building a website, chances are that you are using a css framework. Bootstrap, Materializecss, Foundation are
some of the big css framework that you can include to your website, but you will only use a small set of the framework and
a lot of unused css styles will be included.
This is where Purgecss comes into play. Purgecss takes your content and your css and matches the selectors used in your files
with the one in your content files. It removes every unused selectors from your css files, resulting in smaller, optimize css
files.
npm i --save-dev purgecss
import Purgecss from "purgecss"
import purgeHtml from "purge-from-html"
const purgeCss = new Purgecss({
content: ["**/*.html"],
css: ["**/*.css"],
extractors: [
{
extractor: purgeHtml,
extensions: ["html"]
}
]
})
const result = purgecss.purge()
const gulp = require('gulp')
const purgecss = require('gulp-purgecss')
gulp.task('purgecss', () => {
return gulp.src('src/**/*.css')
.pipe(purgecss({
content: ["src/**/*.html"]
}))
.pipe(gulp.dest('build/css'))
})
const path = require('path')
const glob = require('glob')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const PurgecssPlugin = require('../../')
const PATHS = {
src: path.join(__dirname, 'src')
}
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader?sourceMap'
})
}
]
},
plugins: [
new ExtractTextPlugin('[name].css?[hash]'),
new PurgecssPlugin({
paths: glob.sync(`${PATHS.src}/*`),
styleExtensions: ['.css']
})
]
}
import { rollup } from 'rollup';
import purgecss from 'rollup-plugin-purgecss';
rollup({
entry: 'main.js',
plugins: [
purgecss({
content: ["index.html"]
})
]
});
purgecss --css <css> --content <content> [option]
Options:
--con, --content glob of content files [array]
-c, --config configuration file [string]
-o, --out Filepath directory to write purified css files to [string]
-w, --whitelist List of classes that should not be removed
[array] [default: []]
-h, --help Show help [boolean]
-v, --version Show version number [boolean]
Purgecss can be adapted to suit your need. If you want to purify exclusively html file, you might want
to consider the purge-from-html extractor.
Purgecss relies on extractors to get the list of selector used in a file.
There are multiples types of files that can contains selectors such as html files, templating files like pug, or even javascript file.
You can use an extractor by settings the extractors option in the purgecss config file.
import purgeJs from "purgecss-from-js"
import purgeHtml from "purge-from-html"
const options = {
content: [],// files to extract the selectors from
css: [],// css
extractors: [
{
extractor: purgeJs,
extensions: ["js"]
},
{
extractor: purgeHtml,
extensions: ["html"]
}
]
}
export default options
Purgecss provides a default extractor that is working with all types of files but can be limited and not fit exactly the type of files that you are using.
The default extractor considers every word of a file as a selector.
The default extractor has a few limitations:
@
.The legacy extractor reproduces the behavior of purifycss. You can use the Legacy extractor by setting the option legacy: true
.
The legacy extractor has a few limitations:
An extractor is a simple class with one method. The method extract
takes the content of a file as a string and return an array of selectors.
By convention, the name of the npm package is purge-from-[typefile]
(e.g. purge-from-pug). You can look at the list of extractor on npm by searching purge-from
.
class PurgeFromJs {
static extract(content) {
// return array of css selectors
}
}
The biggest flaw with purifycss is its lack of modularity. It is also is biggest benefit, purifycss can work with any files, not just html or javascript. But purifycss works by looking at all the words in the files and comparing them with the selectors in the css. Every words is consider a selector, which means that a lot of selectors can be consider used because you have the selector name in a paragraph or somewhere in your files.
Purgecss fixes this problem by providing the possibility to create an extractor, an extractor is a function that takes the content
of a file and extract the list of css selectors in it. It allows a perfect removal of unused css. The extractor can used a parser
that returns an ast and then looks through it to select the css selectors. That is the way purge-from-html
works.
You can specified which selectors you want to use for each types of files, and so, get the most accurate results.
You can still use the default or the legacy extractor that will act the same way as purifycss.
As indicated in its Readme, Uncss works the following way:
Because of the emulation of html, and the execution of javascript, uncss is effective at removing unused selectors from web application.
But the emulation can have a cost in term of performance and practicality. Uncss works by emulating the html files. To remove unused css
from pug template files, you will need to convert pug to html and then emulate the page inside jsdom and uncss will run document.querySelector
on each selectors and step 4.
Uncss by its design is probably the most accurate tool to remove css out of a web application at this moment.
Purgecss does not have an extractor right now for javascript files. But because of its modularity, developers can create an extractor for specific framework (vue, react, aurelia) and files (pug, ejs) and get the most accurate result without the need of emulation.
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
Purgecss use SemVer for versioning.
Purgecss was originally thought as the v2 of purifycss. And because of it, it is greatly inspired by it.
The plugins such as purgecss-webpack-plugin are based on the purifycss plugin.
Below is the list of the purifycss repositories:
This project is licensed under the MIT License - see the LICENSE file for details.
The extractors needs to be defined from the more specific to the less specific. Meaning that you need to define js
extractor after ejs
. So the js
extractor will not be selected for ejs files.
You can specified extensions like
.es.js
.
If you are using the default or legacy extractor, look here. Head over the repository of the extractor and open an issue. Be as precise as possible when describing the issue, provide the css file and content file if possible.
FAQs
Remove unused css selectors
We found that purgecss demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.