Giter Club home page Giter Club logo

gatsby-plugin-purgecss's Introduction

Gatsby Plugin Purgecss npm version npm downloads

Works with Gatsby v2/v3/v4/v5

Node.js CI CircleCI Coverage Status Renovate badge Known Vulnerabilities Security Score tested with jest

Support me on Github Support me on KoFi

What is this plugin about?

Remove unused css from css/sass/less/stylus files and modules in your Gatsby project using purgecss. πŸŽ‰. Supports tailwind, bootstrap, bulma etc.


⚠️ NOTE: This is NOT an install and forget type plugin. By default, it may remove required styles too.

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 - includes migration to v6 guide β€’ Older v5 doc

Demo

When used in gatsby-starter-bootstrap

demo

When used in gatsby-starter-bootstrap-cv (installed by default)

demo

Supported files

Installation

npm i gatsby-plugin-purgecss

Usage

Add the plugin AFTER other css/postcss plugins

// gatsby-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
        // ignore: ['/ignored.css', 'prismjs/', 'docsearch.js/'], // Ignore files/folders
        // purgeOnly : ['components/', '/main.css', 'bootstrap/'], // Purge only these files/folders
        purgeCSSOptions: {
          // https://purgecss.com/configuration.html#options
          // safelist: ['safelist'], // Don't remove this selector
        },
        // More options defined here https://purgecss.com/configuration.html#options
      },
    },
  ],
};

Read about all the available options.

TLDR

  • Define options in gatsby-config.js, not purgecss.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 match mySelector.
  • 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 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.
  • 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.

Help! Purgecss breaks my site

Diagnosing the issue

  • 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.

Issues

This section documents purgecss behavior in removing unused css. Most of the rules apply in any project and is not gatsby-plugin-purgecss specific.

Issue 1: CSS file not getting purged

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.

Issue 2: Selectors with dashes in name gets removed when used with named imports

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`} /> βœ…

Issue 3: Styles getting purged even though the script file has selector names

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.

Issue 4: Getting "Could not parse file, skipping. Your build will not break."

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.

Issue 5: Using npm packages with components which import css files

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:

  1. Ignore the file completely using the ignore option
  2. Whitelist the required selectors as described in the next section.
  3. 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}')
];

Issue 6: Works in develop, breaks in build

gatsby-plugin-purgecss by default does not run when using gatsby develop.

Issue 7: Selectors in markdown (.md, .mdx) files are getting removed

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.

Whitelist Solutions

You can use any of these techniques to stop purgecss from removing required styles

1. Whitelist the selector using the safelist option in gatsby-config.js

purgeCSSOptions: {
  safelist: ['my-selector'], // Don't remove this selector
}

PurgeCSS docs.
Read about safelist option.

2. Use a JavaScript comment

// my-selector
<div className={style.mySelector} />

This comment can be in any script file inside src.

3. Use Regex pattern to exclude many selectors

safelist option is available from purgecss

purgeCSSOptions: {
  safelist: [/^btn/], // Don't remove this selector
}

4. Use purgecss ignore comment in css file

/* purgecss ignore */
.my-selector {
  color: 'white';
}

This comment will ignore the selector on the next line.

5. Use purgecss ignore block comments in css file

/* purgecss start ignore */
button {
  color: 'white';
}
.yo {
  color: 'blue';
}
/* purgecss end ignore */

This comment pair will ignore all css selectors between them.

6. Ignore files and folder using the ignore options

ignore: [
  'ignoredFile.css',
  'ignoredFolder/',
  'sub/folder/ignore/',
  'inFolder/file.css',
];

Note: always use forward slash / for folders, even on Windows.
Read about ignore option.

7. Purge only specified files and skip everything else

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.

8. For selector with dashes in them and using named imports

You could write it like className={style['my-selector']} instead.

Improving Purgecss selector detection

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.

Important Notes

Running

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.

Size reporting

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.

Selector matching

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/.

Safelist ['html', 'body']

Since html and body tags do not appear in src/ files, it is safelisted by default to not be removed.

Webpack loader order

Sass/Less/Stylus(or any other loader) -> PostCSS -> PurgeCSS -> CSSLoader -> (CSSExtract/StyleLoader)
Note: Sass/Less/Stylus @imports are executed before this plugin, therefore, it won't see the @imported files as separate files.

Options

Options can be specified in your gatsby-config.js file like so:

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-purgecss',
      options: {
        printRejected: true,
        purgeCSSOptions: {
          safelist: [],
        },
      },
    },
  ],
};

Purgecss options can be specified under the purgeCSSOptions key.

Read about all the purgecss options

printRejected

Print the list of removed selectors
printRejected: boolean

printRejected: 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

printAll

Enables printRejected to print all the rejected selectors.
(Output can get messy)
printAll: boolean

printAll: true;

Needs printRejected option to be true.
default: false

purgeOnly

Only purge these files/folders.
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: []

ignore

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: []

tailwind

Enable Tailwind support.

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.

tailwind: boolean

tailwind: true;

Uses extractors needed for parsing tailwind class names.
Enable if you are using tailwindcss.
default: false

develop

Enable plugin while using gatsby develop.
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

debug

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

printSummary

Print the total removed css stats.
printSummary: boolean

printSummary: true;

default: true

safelist - from purgecss

Stops from removing these selectors.
safelist: Array<string>

purgeCSSOptions: {
  safelist: ['my-selector', 'footer'];
}

More options for safelist

Note: do NOT add . or # for classes and ids.
'html', 'body' are always safelisted.
Since v2.3.0 manually including 'html', 'body' is no longer required.
default: []

content - from purgecss

Files to search for selectors.
content: Array<string>

purgeCSSOptions: {
  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}')]

Other options from purgecss

Read about other purgecss options.

Versioning

gatsby-plugin-purgecss uses SemVer for versioning.

Acknowledgment

This project was made possible due to the incredible work done on the following projects:

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Hey πŸ‘‹ 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. Your contribution is greatly appreciated and will motivate me to continue to support developing my packages which you may have used.

Support me on Github Support me on KoFi

gatsby-plugin-purgecss's People

Contributors

anantoghosh avatar dependabot[bot] avatar greenkeeper[bot] avatar lekoarts avatar lpmi-13 avatar neilime avatar renovate-bot avatar renovate[bot] avatar samselikoff avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

gatsby-plugin-purgecss's Issues

Using Tailwind with new extensions, like MDX

I added MDX and noticed some Tailwind classes were being incorrectly purged from my MDX files. Looking at the source I see that the Tailwind extractor only applies to these extensions:

extensions: ['js', 'ts', 'jsx', 'tsx']

Would it be possible to generalize it a bit, ideally so it respects the content option? (I had already updated that to include mdx extension types).

TypeScript support

Hi,

Would you consider adding support for TypeScript ?

I have this message when I'm trying to use the plugin in a .tsx file :

TS7016: Could not find a declaration file for module 'gatsby-plugin-breadcrumb/'. '****/node_modules/gatsby-plugin-breadcrumb/index.js' implicitly has an 'any' type. Β Β Try 'npm i --save-dev @types/gatsby-plugin-breadcrumb' if it exists or add a new declaration (.d.ts) file containing 'declare module 'gatsby-plugin-breadcrumb/';'

Thanks

Purge specific files is ignoring with build command

I have found that ignore and purgeOnly options work with gatsby develop but are ignored with gastby build.

If I check the removed selectors everything looks fine, exactly the same happens in develop and build, but in the latter finally all the CSS is purged ignoring the restrictions.

gatsby-plugin-purgecss: Only processing...

image

gatsby: 2.24.9
gatsby-plugin-less: 4.0.6
gatsby-plugin-sass: 2.3.17
gatsby-plugin-purgecss: 5.0.0

The gatsby-plugin-purgecss configuration is right after gatsby-plugin-less

how to whitelist a Loadable component ?

I am using a Loadable component. That components has some elements that use css selectors. But as this component is Loadable gatsby-plugin-purgecss removes the selectors inside that component.

Is there a way to solve this issue ?

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

File: renovate.json
Error type: Invalid JSON (parsing failed)
Message: Syntax error: expecting end of expression or separator near ue
"pack

Gatsby 5 Peer Dependency Support?

Verify if it is a postcss bug
First verify that gatsby-plugin-purgecss is working by setting the option printRejected: true which will print out the list of removed selectors.
If the plugin is working, but the css is not getting purged as you would have hoped then it's very likely a purgecss issue. File for purgecss related bugs here https://github.com/FullHuman/purgecss/issues.

  • I have verified that this is not a purgecss issue.

Describe the bug
Gatsby 5 is out, but gatsby-plugin-purgecss only supports gatsby@"^2.0.0 || ^3.0.0 || ^4.0.0"

To Reproduce
Sample package.json to repro:

  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "gatsby-plugin-purgecss": "^6.1.2",
    "gatsby": "^5.1.0"
  }
}

Error with npm:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/gatsby
npm ERR!   gatsby@"^5.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer gatsby@"^2.0.0 || ^3.0.0 || ^4.0.0" from [email protected]
npm ERR! node_modules/gatsby-plugin-purgecss
npm ERR!   gatsby-plugin-purgecss@"^6.1.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Configs

  • I have removed all personal information.

Expected behavior
Support latest gatsby version as a peer dependency

Additional information
n/a

purgeCSSOptions.content override is not working

  • I have verified that this is not a purgecss issue.

Describe the bug
Custom purgeCSSOptions.content override is not applied (because it always uses default value).

Line with bug - permalink

  void new Purgecss()
    .purge({
      ...options.purgeCSSOptions,
      css: [{ raw: source }],
      content: [path.src],
    })

content: [path.src] will always override same property from options.purgeCSSOptions

To Reproduce
Try to use purgeCSSOptions.content override.

Expected behavior
Custom purgeCSSOptions.content override is working.

Run purgecss in gatsby develop mode

Is your feature request related to a problem? Please describe.
I noticed that purge-css is only running during on gatsby build. It would be really awesome to have the possibility to run this using gatsby develop. It may be extremely complicated to implement, but maybe i'm missing something here

Describe the solution you'd like
If a change is happening the code during running the gatsby develop, gatsby picks up that change and reloads the page in the browser.It would be really nice if purgecss could run before the site is delivered

Describe alternatives you've considered

Additional context
Please close this issue if this is already implemented, i was not seeing any sign in the code for this, but again, maybe i'm missing something

How to specify custom tailwind config file?

It seems that the warning

Tailwind is not purging unused styles because no template paths have been provided.
If you have manually configured PurgeCSS outside of Tailwind or are deliberately not
removing unused styles, set `purge: false` in your Tailwind config file to silence
this warning.

keeps coming when running gatsby build.
Not sure how to provide the template path.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update jest monorepo to v29 (major) (@types/jest, jest, ts-jest)
  • chore(deps): update yarn to v4
  • fix(deps): update dependency purgecss to v6

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

circleci
.circleci/config.yml
github-actions
.github/workflows/node.js.yml
  • actions/checkout v3
  • actions/setup-node v3
  • actions/cache v3
nodenv
.node-version
  • node 18
npm
package.json
  • yarn 3.3.1
packages/gatsby-plugin-purgecss/package.json
  • fs-extra ^11.1.0
  • loader-utils ^3.2.1
  • merge-anything ^5.1.4
  • purgecss ^4.1.3
  • @release-it/conventional-changelog ^8.0.0
  • @types/fs-extra ^11.0.0
  • @types/jest ^27.5.2
  • @types/loader-utils ^2.0.3
  • @types/node ^18.11.18
  • @types/webpack ^5.28.0
  • @typescript-eslint/eslint-plugin ^7.0.0
  • coveralls ^3.1.1
  • eslint ^9.0.0
  • eslint-config-good-code ^1.1.0
  • eslint-plugin-sonarjs ^0.25.0
  • eslint-plugin-unicorn ^52.0.0
  • execa ^8.0.0
  • gatsby ^5.3.3
  • jest ^27.5.1
  • release-it ^17.0.0
  • ts-jest ^27.1.5
  • ts-node ^10.9.1
  • typescript ^5.0.0
  • gatsby ^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0
packages/test_build/package.json
  • gatsby ^5.3.3
  • gatsby-plugin-less ^7.3.0
  • gatsby-plugin-sass ^6.3.1
  • gatsby-plugin-stylus ^5.3.0
  • less ^4.1.3
  • react ^18.2.0
  • react-dom ^18.2.0
  • sass ^1.57.1

  • Check this box to trigger a request for Renovate to run again on this repository

Run after gatsby-plugin-postcss to allow usage with TailwindCSS

Thanks for creating this!

I use TailwindCSS + PurgeCSS with Gatsby via a custom setup in gatsby-node.js. It works just fine, but it would be nice to hide the implementation details in a plugin like this one.

However, I notice in the docs that this plugin cannot be used with postcss because:

gatsby-plugin-purgecss is executed before postcss loader

Is there a reason for this order? If possible, it would be useful to run purgecss after postcss to allow TailwindCSS or other setups that require postcss to run first.

Disable print with the tailwind option

Is your feature request related to a problem? Please describe.
The plugin log a lot of content, logging service have a log size.

Describe the solution you'd like
A simpler option used to disable large printing in console

An in-range update of less is breaking the build 🚨

Version 3.8.0 of less was just published.

Branch Build failing 🚨
Dependency less
Current Version 3.7.1
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

less is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 3 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

className styles are purged if `purge` object is present in tailwind.config.js

Describe the bug
since purgecss is now included in tailwind, className styles appear to be purged if purge object is present in tailwind.config.js even if the purge object is empty {}

To Reproduce

"gatsby": "^2.24.79",
"gatsby-plugin-postcss": "^3.0.3",
"gatsby-plugin-purgecss": "^5.0.0",
"tailwindcss": "^1.9.4"

Expected behavior
tailwind styles in className should not be purged

Additional information
This may just be a case of adding documentation to ensure the purge: {} object is not present on the tailwind config when using gatsby-plugin-purgecss

Tailwind does actually give a warning suggesting this

warn - Tailwind is not purging unused styles because no template paths have been provided.
warn - If you have manually configured PurgeCSS outside of Tailwind or are deliberately not removing unused styles, set `purge: false` in your Tailwind config
warn - https://tailwindcss.com/docs/controlling-file-size/#removing-unused-css

basically set purge: false in tailwind.config.js if using gatsby-plugin-purgecss should fix it I think

Option to run against rendered html

There was a previous ticket that was similar, but not was closed because it had a slightly different problem.

I want Purgecss to run run against the rendered html, not against the jsx components. I have a CMS that sends classes from a color swatch picker. I don't want to whitelist all of them, my css file can go from 40kb up to 2020kb.

Having the option to parse the final rendered html instead would make this easy, but I'm guessing the final html isn't ready at the point the css file is being prepared?

Remove css classes that are not present in the rendered html file

Let's say that we have the fallowing code

import React from 'react'
import classnames from 'classnames'
import '@material/button/mdc-button.scss'

const Button = ({ raised, unelevated, outlined, dense, className, children }) => (
  <button
    className={classnames('mdc-button', className, {
      'mdc-button--raised': raised,
      'mdc-button--unelevated': unelevated,
      'mdc-button--outlined': outlined,
      'mdc-button--dense': dense
    })}
  >
    {children}
  </button>
)

export default Button

Expected behavior
If in my app I only use <Button> and <Button raised>, mdc-button and mdc-button--raised should be kept, but mdc-button--unelevated, mdc-button--outlined and mdc-button--dense should be discarded.

Current behavior
All css classes mentioned above are kept.

Possible solution
Use the server side rendered html to determine exactly what css classes are being used and which are not. Inside gatsby-ssr.js you can get the html, but I do not know how to get the css.

If it helps here is a snippet that would get the body component of the html .

const { renderToString } = require('react-dom/server');

exports.replaceRenderer = ({ bodyComponent }) => {
  const bodyHTML = renderToString(bodyComponent);
}

Remove css classes from a theme

Is your feature request related to a problem? Please describe.
purgecss will purge all classes from themes (other than the current project directory).

For example, a theme can have a file ArticleTemplate.js that includes Tailwind classes. These classes will be purged by gatsby-plugin-purgecss.

Describe the solution you'd like
gatsby-plugin-purgecss will recursively check all Gatsby themes/plugins before purging css.

This would provide the best user experience as well as the expected behavior as Gatsby themes are going to be a big part of Gatsby in the future.

Describe alternatives you've considered
When registering gatsby-plugin-purgecss, I think an extra option of include can be helpful. Something like this:

module.exports = {
  plugins: [
    {
      resolve: "gatsby-plugin-purgecss",
      options: {
        include: [require("my-gatsby-theme-1"), require("my-gatsby-theme-2")]
      }
    }
  ]
}

With this, purgecss will also check these directory before purging the classes.

Rerun purgecss on changes during development

Is your feature request related to a problem? Please describe.
I am not quite sure if this is a bug or intended behaviour. When running this plugin with develop: true the css is purged which helps to keep the development environment act like production. But code changes like adding new classes to a component will not rerun purgecss. Therefore I need to restart gatsby develop to see the changes when using new classes.

Describe the solution you'd like
it would be great to use purgecss during development and still see all changes resulting from new classes right away.

Not understanding how to configure content option. Documentation unclear

Verify if it is a postcss bug
First verify that gatsby-plugin-purgecss is working by setting the option printRejected: true which will print out the list of removed selectors.
If the plugin is working, but the css is not getting purged as you would have hoped then it's very likely a purgecss issue. File for purgecss related bugs here https://github.com/FullHuman/purgecss/issues.

  • I have verified that this is not a purgecss issue.

Describe the bug
Please provide clearer documentation on the content option. I have read through the section on it and googled regex patterns but cannot quite understand what the snippet of code below is doing or how it works. I need to modify this so that css from npm packages like bootstrap is not removed from my site, but cannot figure out how to change this code to get that to work and what each part of the code means. It would be very helpful if you dissected the code and provided explanations of each part, for example what /**/ does, what (*.d) does, what {ts,js} does, etc.

content: [
path.join(process.cwd(), 'src/**/!(.d).{ts,js,jsx,tsx}'),
path.join(process.cwd(), 'anotherFolder/!(
.d).{ts,js,jsx,tsx}')
];

To Reproduce
Add npm packages such as bootstrap to a site that uses purgecss and it will not work correctly because the css in the package will be removed.

Configs
content: [
path.join(process.cwd(), 'src/**/!(.d).{ts,js,jsx,tsx}'),
path.join(process.cwd(), 'anotherFolder/!(
.d).{ts,js,jsx,tsx}')
];
Please remove any personal information present in the files.

  • I have removed all personal information.

Expected behavior
CSS from bootstrap and other npm packages is not purged

Additional information
N/A

PurgeCss is not working with tailwindui

I have a gatsby-theme project and I'm using tailwindui for designing UI elements.
After enabling gatsby-plugin-purgecss, the design is crashed. PurgeCss removed tailwindui style completely.

gatsby-config.js

....
return {
       plugins: [
           `gatsby-plugin-postcss`,
           {
               resolve: `gatsby-plugin-purgecss`,
               options: {
                   printRejected: true,
                   develop: false,
                   tailwind: true,
               }
           }
       ]
   }
...

post.config.js

const config = require("./tailwind.config");

module.exports = () => ({
    plugins: [require("tailwindcss")(config)],
});

tailwind.config.js

module.exports = {
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [
      require('@tailwindcss/ui')
  ],
};

Invalid syntax error

Verify if it is a postcss bug

  • I have verified that this is not a purgecss issue.

Describe the bug

Error: /Users/venkateshs/bhava/apps/portfolio2018/node_modules/gatsby-plugin-purgecss/node_modules/fs-extra/lib/mkdirs/make-dir.j s:86
} catch {
^
SyntaxError: Unexpected token {

To Reproduce
Installed the plugin
Added it to the last of my plugin list
ran gatsby build

Configs

As mentioned in the documentation

  • I have removed all personal information.

Expected behavior
For the plugin to be properly installed and purge css on production

Support for reactstrap or third party react elements

What's the problem?
I also use reactstrap with Gatsbyjs and your plugin and would like to continue using it. Unfortunately the CSS classes are removed from reactstrap. Give you a solution or can you add a feature that takes third party react elements into account?

Describe the solution you'd like
An automatic detection of CSS that detects third party react elements or a feature like tailwind: true

classes added by clsx not in css

Hee there,

i'm trying to use clsx to do some logic for dynamicly building the classes based on the props of a component. The classes are all bootstrap classes that are added and formed by clsx.
am i correct in assuming purgecss only reads the actually added names in className attributes in the js files? and not also the dynamically created ones inside a component or using clsx?

i currently have a button component like this

import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';

const Button = ({ color, outline, size, component, href, children, className, ...rest }) => {
  const Component = component || href !== undefined ? 'a' : 'button';

  return (
    <Component
      href={href}
      className={clsx(
        'btn',
        {
          [`btn-${outline ? 'outline-' : ''}${color}`]: color,
          [`btn-${size}`]: ['sm', 'lg'].includes(size),
        },
        className,
      )}
      {...rest}
    >
      {children}
    </Component>
  );
};

Button.propTypes = {
  children: PropTypes.any.isRequired,
  className: PropTypes.string,
  color: PropTypes.oneOf(['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'dark', 'light', 'link']),
  component: PropTypes.any,
  href: PropTypes.string,
  size: PropTypes.oneOf(['sm', 'md', 'lg']),
  outline: PropTypes.bool,
};

Button.defaultProps = {
  className: undefined,
  color: 'primary',
  component: undefined,
  href: undefined,
  size: 'md',
  outline: false,
};

export default Button;

when i use this in a page component like this

<Button size="lg" color="secondary" type="button">
  click me
</Button>

it purges all button classes defined by bootstrap. Is there a way of fixing this without the need to whitelist everything that breaks?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.