@fullhuman/purgecss-from-jsx
v9.1.0
Published
JSX extractor for PurgeCSS
Readme
@fullhuman/purgecss-from-jsx
JSX extractor for PurgeCSS. This extractor parses JSX files (React, Preact, etc.) and extracts used selectors from component names, className, and id attributes.
Installation
npm install @fullhuman/purgecss-from-jsx --save-devUsage
With PurgeCSS
import { PurgeCSS } from "purgecss";
import purgeFromJsx from "@fullhuman/purgecss-from-jsx";
const result = await new PurgeCSS().purge({
content: ["**/*.jsx"],
css: ["**/*.css"],
extractors: [
{
extractor: purgeFromJsx(),
extensions: ["jsx"],
},
],
});With Custom Acorn Options
You can pass custom acorn parser options:
import purgeFromJsx from "@fullhuman/purgecss-from-jsx";
const extractor = purgeFromJsx({
ecmaVersion: 2020,
sourceType: "module",
});Standalone
You can use the extractor standalone to extract selectors from JSX content:
import purgeFromJsx from "@fullhuman/purgecss-from-jsx";
const jsx = `
function App() {
return (
<div className="container">
<Header id="main-header" />
<button className="btn btn-primary">Click me</button>
</div>
);
}
`;
const selectors = purgeFromJsx()(jsx);
console.log(selectors);
// ["div", "container", "Header", "main-header", "button", "btn", "btn-primary"]API
purgeFromJsx(options?: acorn.Options): (content: string) => string[]
Creates an extractor function for JSX content.
Parameters
options(optional) - Acorn parser options. Defaults to{ ecmaVersion: "latest" }
Returns
A function that takes JSX content as a string and returns an array of selectors.
What It Extracts
The extractor parses JSX and extracts:
- Component names - JSX element names (e.g.,
div,Header,MyComponent), including elements inside the value of another attribute (e.g.,icon={<Icon />}) - className values - String values from
classNameattributes, split by whitespace - id values - String values from
idattributes
When className or id is an expression, every string in it is extracted, as well as the static parts of template literals and the keys of object literals. For example, className={active ? "on" : "off"} gives on and off, className={`card ${size}`} gives card, and className={clsx({ active: isActive })} gives active.
Example
<Card className="card card-primary" id="featured-card">
<CardHeader />
<CardBody className="p-4" />
</Card>Extracted selectors: ["Card", "card", "card-primary", "featured-card", "CardHeader", "CardBody", "p-4"]
Limitations
- Only extracts static string values from
classNameandid - Values computed at runtime, like
className={styles.container}or thesizeofclassName={`btn-${size}`}, are not extracted - For dynamic class names, consider using PurgeCSS's safelist option
License
MIT
