For Gatsby 2 only
Remove unused css from css/sass/less/stylus files and modules in your Gatsby project using purgecss. 🎉. Supports tailwind, bootstrap, bulma etc.
Please read Help! Purgecss breaks my site 😯 to make sure gatsby-plugin-purgecss does not cause you issues and TLDR for the important bits
📘 Read the latest docs here. • Changelog •
When used in gatsby-starter-bootstrap
When used in gatsby-starter-bootstrap-cv (installed by default)
.css
,.module.css
.scss
,.sass
,.module.scss
,.module.sass
(via gatsby-plugin-sass).less
,.module.less
(via gatsby-plugin-less).styl
,.module.styl
(via gatsby-plugin-stylus)
npm i gatsby-plugin-purgecss
Add the plugin AFTER other css/postcss plugins
// gatsy-config.js
module.exports = {
plugins: [
`gatsby-plugin-stylus`,
`gatsby-plugin-sass`,
`gatsby-plugin-less`,
`gatsby-plugin-postcss`,
// Add after these plugins if used
{
resolve: `gatsby-plugin-purgecss`,
options: {
printRejected: true, // Print removed selectors and processed file names
// develop: true, // Enable while using `gatsby develop`
// tailwind: true, // Enable tailwindcss support
// whitelist: ['whitelist'], // Don't remove this selector
// ignore: ['/ignored.css', 'prismjs/', 'docsearch.js/'], // Ignore files/folders
// purgeOnly : ['components/', '/main.css', 'bootstrap/'], // Purge only these files/folders
}
}
]
};
Read about all the available options.
- Define options in
gatsby-config.js
, notpurgecss.config.js
. - If using tailwindcss, use the
tailwind: true
option. - Use
printRejected: true
option to print the removed selectors. - Only files processed by Webpack will be purged.
my-selector
will not matchmySelector
.- Whitelist required selectors or ignore files/folder using the Whitelist Solutions guide.
- Ignore complete packages with
ignore: ['packagename/']
. - To only purge specific files/packages use
purgeOnly: ['fileOrPackage/']
. - Only
js, jsx, ts, tsx
files are scanned for selectors by default. If you want to addmd
ormdx
usecontent: [path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx,md,mdx}')]
or better, just whitelist the required selectors.
- Use
printRejected: true
option which will print the filenames and the selectors which were removed. - Identify which of the required selectors were removed.
- Whitelist the required selectors or completely ignore files using Whitelist Solutions guide.
- Look at the Issues section to understand why/how the purge was performed.
This section documents purgecss behavior in removing unused css. Most of the rules apply in any project and is not gatsby-plugin-purgecss
specific.
For gatsby-plugin-purgecss
to work on a css file it must be imported by a script file inside your src folder. This plugin depends on webpack to process css. If webpack does not use the css file then gatsby-plugin-purgecss
cannot process it.
Also, make sure that you included the plugin after sass/less/stylus/postcss plugins.
For eg: style.css
.my-selector { color: 'white' }
index.js
// Named import
import style from './style.css';
...
<div className={style.mySelector} /> ❌
Here .my-selector
will get removed since purgecss by default cannot match it with mySelector
.
Read how to solve this issue in the "Whitelist Solutions" section.
Note: Directly importing and using the selector name as is will work as intended
import './style.css';
<div className={`my-selector`} /> ✅
Make sure that the script file is in the src
folder.
If you want to look for selectors in another folder, use the content
option.
If you use postcss syntax based plugins then read this.
Something is wrong. Good news is gatsby-plugin-purgecss
should not cause any issue in such cases, files which could not be parsed will be skipped. If you want to diagnose the problem then use the debug
option. Also, feel free to create a GitHub issue.
If you import a npm package which imports its own styles locally, then gatsby-plugin-purgecss will incorrectly remove all the css imported by the package. It's because by default the selectors are only matched with the files under 'src' folder.
To get around this, you could:
- Ignore the file completely using the
ignore
option - Whitelist the required selectors as described in the next section.
- Use the
content
option and add the package's path. Eg:
content: [
path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx}'),
path.join(process.cwd(), 'node_modules/my-npm-package/folder-to-match/!(*.d).{ts,js,jsx,tsx}')
];
gatsby-plugin-purgecss
by default does not run when using gatsby develop
.
Markdown files are not scanned for selectors by default.
Use the content
option. to add them.
content: [path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx,md,mdx}')]
Note: This may decrease the amount of styles removed because purgecss will consider every word in the markdown file to be a selector.
If possible, just whitelist the required selectors instead of using this option.
You can use any of these techniques to stop purgecss from removing required styles
whitelist: ['my-selector']
// my-selector
<div className={style.mySelector} />
This comment can be in any script file inside src
.
whitelistPatterns
option is available from purgecss
whitelistPatterns: [/^btn/]
For eg, this pattern will whitelist all selectors starting with btn: btn btn-primary btn-secondary etc.
Read about whitelistPatterns option.
Look at the whitelistPatternsChildren
option in purgecss to also whitelist children of the selectors.
/* purgecss ignore */
.my-selector { color: 'white' }
This comment will ignore the selector on the next line.
/* purgecss start ignore */
button { color: 'white' };
.yo { color: 'blue' };
/* purgecss end ignore */
This comment pair will ignore all css selectors between them.
ignore: ['ignoredFile.css', 'ignoredFolder/', 'sub/folder/ignore/', 'inFolder/file.css']
Note: always use forward slash /
for folders, even on Windows.
Read about ignore option.
purgeOnly: ['/mainstyles.css', 'node_modules/bootstrap']
Note: always use forward slash /
for folders, even on Windows.
Good if you only need to purge some large css library and not touch anything else.
Read about purgeOnly option.
You could write it like className={style['my-selector']}
instead.
Purgecss relies on extractors to get the list of selector used in a file. The default extractor considers every word of a file as a selector. You could use your own extractor (or get one made by other community members) to improve detection and further decrease your css file size. Read more at Purgecss docs.
If you do find/write a better extractor suited for Gatsby, please help me add it to the docs.
By default, this plugin only runs when building the project (gatsby build
).
It will print the amount of css removed.
To run it while using gatsby develop
, use the develop: true
option.
The size reported by this plugin is the approximate size of the css content before any optimizations have been performed.
The actual file size should be smaller.
This plugin loads css files (or transformed output from css plugins) and searches for matching selectors in js, jsx, ts, tsx files in src/
. It does not know which css file belongs to which source file. Therefore, for eg., if there is a class .module
in some css file, it will not be removed if it used in any script file under src/
.
Since html and body tags do not appear in src/
files, it is whitelisted by default to not be removed.
Since v2.3.0, manually including 'html', 'body' is no longer required.
Sass/Less/Stylus(or any other loader) -> PostCSS -> PurgeCSS -> CSSLoader -> (CSSExtract/StyleLoader)
Note: Sass/Less/Stylus @import
s are executed before this plugin, therefore, it won't see the @import
ed files as separate files.
Since v3, gatsby-plugin-purgecss
should work with other postcss plugins.
For older versions:
gatsby-plugin-purgecss
is executed before postcss loader and can only purge css syntax. If you are using any syntax based postcss plugin, then it may not get purged. In such cases you will see "Could not parse file, skipping. Your build will not break." message. gatsby-plugin-purgecss
will simply ignore the file and continue without issue.
It would be better if you use purgecss postcss plugin directly instead.
This plugin supports most purgecss options as is (except css
).
Options can be specified in your gatsby-config.js
file like so:
module.exports = {
plugins: [
{
resolve: 'gatsby-plugin-purgecss',
options: {
printRejected: true,
}
}
]
};
Print the amount of css removed
rejected: boolean
rejected: true
default: true
Print the list of removed selectors
printRejected: boolean
printRejected: true
Needs rejected
option to be true.
It will print maximum of 100 removed selector per file to keep the output readable.
To view all the removed selector enable the printAll
option.
default: false
Enables printRejected
to print all the rejected selectors.
(Output can get messy)
printAll: boolean
printAll: true
Needs printRejected
option to be true.
default: false
Stops from removing these selectors.
whitelist: Array<string>
whitelist: ['my-selector', 'footer']
Note: do NOT add .
or #
for classes and ids.
'html'
, 'body'
are always whitelisted.
Since v2.3.0 manually including 'html', 'body' is no longer required.
default: []
Only purge these files/folders.
Added in v3.1.0.
ignore: Array<string>
purgeOnly: ['/main.css', 'bootstrap/', 'node_modules/font-awesome/']
Note: always use forward slash /
for folders, even on Windows.
Can be combined with the ignore
option.
default: []
Stop these files or folders from getting purged.
ignore: Array<string>
ignore: ['/ignoredFile.css', 'ignoredFolder/', 'sub/folder/ignore/', 'inFolder/file.css']
Note: always use forward slash /
for folders, even on Windows.
default: []
Enable Tailwind support.
Added in v3.
tailwind: boolean
tailwind: true
Uses extractors needed for parsing tailwind class names.
Enable if you are using tailwindcss.
default: false
Enable plugin while using gatsby develop
.
Added in v3.
develop: boolean
develop: true
This does not print the total css removed.
To see what is being removed, use it with the printRejected option.
default: false
Enable debugging
debug: boolean
debug: true
It will write two files to disk.
gatsby-plugin-purgecss-debug-config.js
with Gatsby's webpack config.
gatsby-plugin-purgecss-debug.js
with the errors encountered.
default: false
Files to search for selectors.
content: Array<string>
content: [
path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx}'),
path.join(process.cwd(), 'anotherFolder/!(*.d).{ts,js,jsx,tsx}')
];
default: [path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx}')]
Whitelist Selectors with Regular Expression
whitelistPatterns: Array<RegExp>
whitelistPatterns: [/button/, /^fa-/, /main$/]
This example will whitelist selectors containing "button", starting with "fa-" and ending with "main".
default: []
Contrary to whitelistPatterns
, it will also whitelist children of the selectors.
whitelistPatternsChildren: Array<RegExp>
whitelistPatternsChildren: [/red$/]
In the example, selectors such as red p
or .bg-red .child-of-bg
will be left in the final CSS.
default: []
Read About other purgecss options.
extractors?: Array<ExtractorsObj>
keyframes?: boolean
fontFace?: boolean
gatsby-plugin-purgecss uses SemVer for versioning.
This project was made possible due to the incredible work done on the following projects:
This project is licensed under the MIT License - see the LICENSE file for details.