UNPKG

17.9 kBMarkdownView Raw
1# Gatsby Plugin Purgecss [![npm version](https://badge.fury.io/js/gatsby-plugin-purgecss.svg)](https://www.npmjs.com/package/gatsby-plugin-purgecss) [![npm downloads](https://img.shields.io/npm/dt/gatsby-plugin-purgecss.svg)](https://www.npmjs.com/package/gatsby-plugin-purgecss)
2Works with Gatsby v2/v3/v4
3
4[![Node.js CI](https://github.com/anantoghosh/gatsby-plugin-purgecss/actions/workflows/node.js.yml/badge.svg)](https://github.com/anantoghosh/gatsby-plugin-purgecss/actions/workflows/node.js.yml)
5[![CircleCI](https://circleci.com/gh/anantoghosh/gatsby-plugin-purgecss/tree/master.svg?style=svg)](https://circleci.com/gh/anantoghosh/gatsby-plugin-purgecss/tree/master)
6[![Coverage Status](https://coveralls.io/repos/github/anantoghosh/gatsby-plugin-purgecss/badge.svg?branch=master)](https://coveralls.io/github/anantoghosh/gatsby-plugin-purgecss?branch=master)
7[![Renovate badge](https://camo.githubusercontent.com/d89df1f233d795498824e8739f439d2172d7ff12/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f72656e6f766174652d656e61626c65642d627269676874677265656e2e737667)](https://renovatebot.com/)
8[![Known Vulnerabilities](https://snyk.io/test/github/anantoghosh/gatsby-plugin-purgecss/badge.svg?targetFile=packages/gatsby-plugin-purgecss/package.json)](https://snyk.io/test/github/anantoghosh/gatsby-plugin-purgecss?targetFile=packages/gatsby-plugin-purgecss/package.json)
9[![Security Score](https://snyk-widget.herokuapp.com/badge/npm/gatsby-plugin-purgecss/badge.svg)](https://snyk.io/advisor/npm-package/gatsby-plugin-purgecss)
10[![tested with jest](https://anantoghosh.github.io/stop-watch/jest_op.svg)](https://github.com/facebook/jest)
11
12<a href="https://ko-fi.com/anantoghosh" rel="nofollow"><img alt="Support me (worldwide)" src="https://anantoghosh.github.io/assets/kofi.svg" height="36" /></a>
13<a href="https://pages.razorpay.com/ananto" rel="nofollow"><img alt="Support me (india)" src="https://anantoghosh.github.io/assets/razorpay.svg" height="36" /></a>
14
15## What is this plugin about?
16
17**Remove unused css from css/sass/less/stylus files and modules in your Gatsby project using [purgecss](https://github.com/FullHuman/purgecss). 🎉. Supports tailwind, bootstrap, bulma etc.**
18
19<hr />
20
21⚠️ NOTE: This is NOT an install and forget type plugin. By default, it may remove required styles too.
22
23**Please read [Help! Purgecss breaks my site](#help-purgecss-breaks-my-site) 😯 to make sure gatsby-plugin-purgecss does not cause you issues and [TLDR](#TLDR) for the important bits**
24
25<hr />
26
27📘 [Read the latest docs here.](https://github.com/anantoghosh/gatsby-plugin-purgecss/) • [Changelog - includes migration to v6 guide](https://github.com/anantoghosh/gatsby-plugin-purgecss/blob/master/packages/gatsby-plugin-purgecss/CHANGELOG.md) • [Older v5 doc](https://github.com/anantoghosh/gatsby-plugin-purgecss/tree/5.0.0)
28
29### Demo
30
31When used in [gatsby-starter-bootstrap](https://github.com/jaxx2104/gatsby-starter-bootstrap)
32
33![demo](https://anantoghosh.github.io/files/gatsby-starter-bootstrap.png)
34
35When used in [gatsby-starter-bootstrap-cv](https://github.com/mhjadav/gatsby-starter-bootstrap-cv) (installed by default)
36
37![demo](https://anantoghosh.github.io/files/gatsby-starter-bootstrap-cv.png)
38
39## Supported files
40
41- `.css` , `.module.css`
42- `.scss`, `.sass`, `.module.scss`, `.module.sass` (via [gatsby-plugin-sass](https://next.gatsbyjs.org/packages/gatsby-plugin-sass/))
43- `.less`, `.module.less` (via [gatsby-plugin-less](https://next.gatsbyjs.org/packages/gatsby-plugin-less/))
44- `.styl`, `.module.styl` (via [gatsby-plugin-stylus](https://next.gatsbyjs.org/packages/gatsby-plugin-sass/))
45
46## Installation
47
48```sh
49npm i gatsby-plugin-purgecss
50```
51
52### Usage
53
54> **Add the plugin AFTER other css/postcss plugins**
55
56```js
57// gatsby-config.js
58module.exports = {
59 plugins: [
60 `gatsby-plugin-stylus`,
61 `gatsby-plugin-sass`,
62 `gatsby-plugin-less`,
63 `gatsby-plugin-postcss`,
64 // Add after these plugins if used
65 {
66 resolve: `gatsby-plugin-purgecss`,
67 options: {
68 printRejected: true, // Print removed selectors and processed file names
69 // develop: true, // Enable while using `gatsby develop`
70 // tailwind: true, // Enable tailwindcss support
71 // ignore: ['/ignored.css', 'prismjs/', 'docsearch.js/'], // Ignore files/folders
72 // purgeOnly : ['components/', '/main.css', 'bootstrap/'], // Purge only these files/folders
73 purgeCSSOptions: {
74 // https://purgecss.com/configuration.html#options
75 // safelist: ['safelist'], // Don't remove this selector
76 },
77 // More options defined here https://purgecss.com/configuration.html#options
78 },
79 },
80 ],
81};
82```
83
84[Read about all the available options.](#options)
85
86## TLDR
87
88- Define options in `gatsby-config.js`, not `purgecss.config.js`.
89- If using tailwindcss, use the [`tailwind: true` option](#tailwind).
90- Use [`printRejected: true`](#printrejected) option to print the removed selectors.
91- Only files processed by Webpack will be purged.
92- `my-selector` will not match `mySelector`.
93- Whitelist required selectors or ignore files/folder using the [Whitelist Solutions](#whitelist-solutions) guide.
94- Ignore complete packages with [`ignore: ['packagename/']`](#ignore).
95- To only purge specific files/packages use [`purgeOnly: ['fileOrPackage/']`](#purgeOnly).
96- Only `js, jsx, ts, tsx` files are scanned for selectors by default. If you want to add `md` or `mdx` use `content: [path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx,md,mdx}')]` or better, just whitelist the required selectors.
97- Tailwind now can use purgecss directly too so you may want to use that. This plugin has the benefit of being able to define more options (ignore, purgeOnly, printRejected etc.) and can purge CSS modules.
98
99## Help! Purgecss breaks my site
100
101### Diagnosing the issue
102
103- Use [`printRejected: true` option](#printrejected) which will print the filenames and the selectors which were removed.
104- Identify which of the required selectors were removed.
105- Whitelist the required selectors or completely ignore files using [Whitelist Solutions](#whitelist-solutions) guide.
106- Look at the [Issues](#issues) section to understand why/how the purge was performed.
107
108### Issues
109
110This section documents purgecss behavior in removing unused css. Most of the rules apply in any project and is not `gatsby-plugin-purgecss` specific.
111
112#### Issue 1: CSS file not getting purged
113
114For `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.**
115
116Also, make sure that you [included the plugin](#usage) after sass/less/stylus/postcss plugins.
117
118#### Issue 2: Selectors with dashes in name gets removed when used with named imports
119
120For eg:
121**style.css**
122
123```css
124.my-selector {
125 color: 'white';
126}
127```
128
129**index.js**
130
131```jsx
132// Named import
133import style from './style.css';
134...
135<div className={style.mySelector} /> ❌
136```
137
138Here `.my-selector` **will get removed** since purgecss by default cannot match it with `mySelector`.
139
140**Read how to solve this issue in the ["Whitelist Solutions"](#whitelist-solutions) section.**
141
142_Note: Directly importing and using the selector name as is will work as intended_
143
144```jsx
145import './style.css';
146<div className={`my-selector`} /> ✅
147```
148
149#### Issue 3: Styles getting purged even though the script file has selector names
150
151Make sure that the script file is in the `src` folder.
152If you want to look for selectors in another folder, use the [`content` option.](#content---from-purgecss)
153
154#### Issue 4: Getting "Could not parse file, skipping. Your build will not break."
155
156> If you use postcss syntax based plugins then read [this](#using-with-postcss-syntax-plugins).
157
158Something 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](#debug). Also, feel free to create a GitHub issue.
159
160#### Issue 5: Using npm packages with components which import css files
161
162If 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.
163To get around this, you could:
164
1651. Ignore the file completely using the [`ignore` option](#ignore)
1662. Whitelist the required selectors as described in the next section.
1673. Use the [`content` option](#content---from-purgecss) and add the package's path.
168 Eg:
169
170```js
171content: [
172 path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx}'),
173 path.join(process.cwd(), 'node_modules/my-npm-package/folder-to-match/!(*.d).{ts,js,jsx,tsx}')
174];
175```
176
177#### Issue 6: Works in `develop`, breaks in `build`
178
179`gatsby-plugin-purgecss` by default does not run when using `gatsby develop`.
180
181#### Issue 7: Selectors in markdown (.md, .mdx) files are getting removed
182
183Markdown files are not scanned for selectors by default.
184Use the [`content` option.](#content---from-purgecss) to add them.
185
186```js
187content: [path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx,md,mdx}')]
188```
189
190Note: This may decrease the amount of styles removed because purgecss will consider every word in the markdown file to be a selector.
191If possible, just whitelist the required selectors instead of using this option.
192
193### Whitelist Solutions
194
195You can use any of these techniques to stop purgecss from removing required styles
196
197#### 1. Whitelist the selector using the safelist option in gatsby-config.js
198
199```js
200purgeCSSOptions: {
201 safelist: ['my-selector'], // Don't remove this selector
202}
203```
204[PurgeCSS docs.](https://purgecss.com/safelisting.html#specific-selectors)
205[Read about safelist option.](#safelist---from-purgecss)
206
207#### 2. Use a JavaScript comment
208
209```jsx
210// my-selector
211<div className={style.mySelector} />
212```
213
214This comment can be in any script file inside `src`.
215
216#### 3. Use Regex pattern to exclude many selectors
217
218`safelist` option is available from purgecss
219
220```js
221purgeCSSOptions: {
222 safelist: [/^btn/], // Don't remove this selector
223}
224```
225
226#### 4. Use purgecss ignore comment in css file
227
228```css
229/* purgecss ignore */
230.my-selector {
231 color: 'white';
232}
233```
234
235This comment will ignore the selector on the next line.
236
237#### 5. Use purgecss ignore block comments in css file
238
239```css
240/* purgecss start ignore */
241button {
242 color: 'white';
243}
244.yo {
245 color: 'blue';
246}
247/* purgecss end ignore */
248```
249
250This comment pair will ignore all css selectors between them.
251
252#### 6. Ignore files and folder using the ignore options
253
254```js
255ignore: [
256 'ignoredFile.css',
257 'ignoredFolder/',
258 'sub/folder/ignore/',
259 'inFolder/file.css',
260];
261```
262
263**Note:** always use forward slash `/` for folders, even on Windows.
264[Read about ignore option.](#ignore)
265
266#### 7. Purge only specified files and skip everything else
267
268```js
269purgeOnly: ['/mainstyles.css', 'node_modules/bootstrap'];
270```
271
272**Note:** always use forward slash `/` for folders, even on Windows.
273Good if you only need to purge some large css library and not touch anything else.
274[Read about purgeOnly option.](#purgeOnly)
275
276#### 8. For selector with dashes in them and using named imports
277
278You _could_ write it like `className={style['my-selector']}` instead.
279
280### Improving Purgecss selector detection
281
282Purgecss 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.
283You could use your own extractor (or get one made by other community members) to improve detection and further decrease your css file size.
284[Read more at Purgecss docs.](https://www.purgecss.com/extractors)
285
286If you do find/write a better extractor suited for Gatsby, please help me add it to the docs.
287
288## Important Notes
289
290### Running
291
292By default, this plugin only runs when building the project (`gatsby build`).
293It will print the amount of css removed.
294To run it while using `gatsby develop`, use the `develop: true` option.
295
296### Size reporting
297
298The size reported by this plugin is the approximate size of the css content _before_ any optimizations have been performed.
299The actual file size should be smaller.
300
301### Selector matching
302
303This 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/`.
304
305### Safelist ['html', 'body']
306
307Since html and body tags do not appear in `src/` files, it is safelisted by default to not be removed.
308
309### Webpack loader order
310
311Sass/Less/Stylus(or any other loader) -> PostCSS -> **PurgeCSS** -> CSSLoader -> (CSSExtract/StyleLoader)
312Note: Sass/Less/Stylus `@import`s are executed before this plugin, therefore, it won't see the `@import`ed files as separate files.
313
314## Options
315
316Options can be specified in your `gatsby-config.js` file like so:
317
318```js
319module.exports = {
320 plugins: [
321 {
322 resolve: 'gatsby-plugin-purgecss',
323 options: {
324 printRejected: true,
325 purgeCSSOptions: {
326 safelist: [],
327 },
328 },
329 },
330 ],
331};
332```
333
334Purgecss options can be specified under the `purgeCSSOptions` key.
335
336> [Read about all the purgecss options](https://purgecss.com/configuration.html#options)
337
338### printRejected
339
340Print the list of removed selectors
341**`printRejected: boolean`**
342
343```js
344printRejected: true;
345```
346
347It will print maximum of 100 removed selector per file to keep the output readable.
348To view all the removed selector enable the [`printAll` option](#printall).
349default: `false`
350
351### printAll
352
353Enables `printRejected` to print all the rejected selectors.
354(Output can get messy)
355**`printAll: boolean`**
356
357```js
358printAll: true;
359```
360
361Needs [`printRejected`](#printrejected) option to be true.
362default: `false`
363
364### purgeOnly
365
366Only purge these files/folders.
367**`ignore: Array<string>`**
368
369```js
370purgeOnly: ['/main.css', 'bootstrap/', 'node_modules/font-awesome/'];
371```
372
373**Note:** always use forward slash `/` for folders, even on Windows.
374Can be combined with the [`ignore` option](#ignore).
375default: `[]`
376
377### ignore
378
379Stop these files or folders from getting purged.
380**`ignore: Array<string>`**
381
382```js
383ignore: [
384 '/ignoredFile.css',
385 'ignoredFolder/',
386 'sub/folder/ignore/',
387 'inFolder/file.css',
388];
389```
390
391**Note:** always use forward slash `/` for folders, even on Windows.
392default: `[]`
393
394### tailwind
395
396Enable Tailwind support.
397> Tailwind now can use purgecss directly too so you may want to use that. This plugin has the benefit of being able to define more options (ignore, purgeOnly, printRejected etc.) and can purge CSS modules.
398
399**`tailwind: boolean`**
400
401```js
402tailwind: true;
403```
404
405Uses extractors needed for parsing tailwind class names.
406Enable if you are using tailwindcss.
407default: `false`
408
409### develop
410
411Enable plugin while using `gatsby develop`.
412**`develop: boolean`**
413
414```js
415develop: true;
416```
417
418This does not print the total css removed.
419To see what is being removed, use it with the [printRejected option](#printrejected).
420default: `false`
421
422### debug
423
424Enable debugging
425**`debug: boolean`**
426
427```js
428debug: true;
429```
430
431It will write two files to disk.
432`gatsby-plugin-purgecss-debug-config.js` with Gatsby's webpack config.
433`gatsby-plugin-purgecss-debug.js` with the errors encountered.
434default: `false`
435
436### printSummary
437
438Print the total removed css stats.
439**`printSummary: boolean`**
440
441```js
442printSummary: true;
443```
444default: `true`
445
446### safelist - from purgecss
447
448Stops from removing these selectors.
449**`safelist: Array<string>`**
450
451```js
452purgeCSSOptions: {
453 safelist: ['my-selector', 'footer'];
454}
455```
456[More options for safelist](https://purgecss.com/safelisting.html#specific-selectors)
457
458**Note:** do NOT add `.` or `#` for classes and ids.
459`'html'`, `'body'` are always safelisted.
460Since v2.3.0 manually including 'html', 'body' is no longer required.
461default: `[]`
462
463### content - from purgecss
464
465Files to search for selectors.
466**`content: Array<string>`**
467
468```js
469purgeCSSOptions: {
470 content: [
471 path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx}'),
472 path.join(process.cwd(), 'anotherFolder/!(*.d).{ts,js,jsx,tsx}'),
473 ];
474}
475```
476
477default: `[path.join(process.cwd(), 'src/**/!(*.d).{ts,js,jsx,tsx}')]`
478
479### Other options from purgecss
480
481[Read about other purgecss options.](https://www.purgecss.com/configuration)
482
483## Versioning
484
485gatsby-plugin-purgecss uses [SemVer](http://semver.org/) for versioning.
486
487## Acknowledgment
488
489This project was made possible due to the incredible work done on the following projects:
490
491- [purgecss](https://github.com/FullHuman/purgecss)
492- [purgecss-loader](https://github.com/americanexpress/purgecss-loader)
493- [gatsby](https://github.com/gatsbyjs/gatsby/)
494
495## License
496
497This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
498
499## Support
500
501Hey 👋 If my packages has helped you in any way, consider making a small donation to encourage me to keep contributing. Maintaining good software takes time and effort and for open source developers there is very less incentives to do so.
502Your contribution is greatly appreciated and will motivate me to continue to support developing my packages which you may have used.
503
504<a href="https://ko-fi.com/anantoghosh" rel="nofollow"><img alt="Support me (worldwide)" src="https://anantoghosh.github.io/assets/kofi.svg" height="36" /></a>
505<a href="https://pages.razorpay.com/ananto" rel="nofollow"><img alt="Support me (india)" src="https://anantoghosh.github.io/assets/razorpay.svg" height="36" /></a>