With Webpack
Start by installing the Webpack plugin as a dev dependency:
1
npm i -D purgecss-webpack-plugin
Copied!
You will need extract-text-webpack-plugin as well.
1
npm i -D extract-text-webpack-plugin
Copied!
1
const path = require('path')
2
const glob = require('glob')
3
const ExtractTextPlugin = require('extract-text-webpack-plugin')
4
const PurgecssPlugin = require('purgecss-webpack-plugin')
5
6
const PATHS = {
7
src: path.join(__dirname, 'src')
8
}
9
10
module.exports = {
11
entry: './src/index.js',
12
output: {
13
filename: 'bundle.js',
14
path: path.join(__dirname, 'dist')
15
},
16
module: {
17
rules: [
18
{
19
test: /\.css$/,
20
use: ExtractTextPlugin.extract({
21
fallback: 'style-loader',
22
use: 'css-loader?sourceMap'
23
})
24
}
25
]
26
},
27
plugins: [
28
new ExtractTextPlugin('[name].css?[hash]'),
29
new PurgecssPlugin({
30
paths: glob.sync(`${PATHS.src}/*`)
31
})
32
]
33
}
Copied!

Options

The options available in the PurgeCSS configuration are also available in the Webpack plugin (except css and content).
  • paths
With the Webpack plugin, you can specify content that should be analyzed by PurgeCSS with an array of filenames. The files can be HTML, Pug, Blade, etc. You can also use a module like glob or glob-all to easily get a list of files.
1
const PurgecssPlugin = require('purgecss-webpack-plugin')
2
const glob = require('glob')
3
const PATHS = {
4
src: path.join(__dirname, 'src')
5
}
6
7
// In the webpack configuration
8
new PurgecssPlugin({
9
paths: glob.sync(`${PATHS.src}/*`)
10
})
Copied!
If you want to regenerate the paths list on every compilation (e.g. with --watch), then you can also pass a function:
1
new PurgecssPlugin({
2
paths: () => glob.sync(`${PATHS.src}/*`)
3
})
Copied!
  • only
You can specify entrypoints to the purgecss-webpack-plugin with the option only:
1
new PurgecssPlugin({
2
paths: glob.sync(`${PATHS.src}/*`),
3
only: ['bundle', 'vendor']
4
})
Copied!
  • whitelist and whitelistPatterns
Similar as for the paths option, you also can define functions for the these options:
1
function collectWhitelist() {
2
// do something to collect the whitelist
3
return ['whitelisted'];
4
}
5
function collectWhitelistPatterns() {
6
// do something to collect the whitelist
7
return [/^whitelisted-/];
8
}
9
10
// In the Webpack configuration
11
new PurgecssPlugin({
12
whitelist: collectWhitelist,
13
whitelistPatterns: collectWhitelistPatterns
14
})
Copied!
Last modified 2yr ago
Copy link
Contents
Options