purgecss
- Version 9.1.0
- Published
- 231 kB
- 4 dependencies
- MIT license
Install
npm i purgecssyarn add purgecsspnpm add purgecssOverview
Core package of PurgeCSS
Contains the core methods to analyze the files, remove unused CSS.
Index
Variables
Functions
Classes
Interfaces
Type Aliases
Variables
variable defaultOptions
const defaultOptions: Options;Modifiers
@public
Functions
function matchesPattern
matchesPattern: (pattern: string | RegExp, value: string) => boolean;Check if a value matches a pattern of the options: a regular expression, or a string written between slashes like "/^btn-/", is tested against the value, any other string matches the value exactly
Parameter pattern
string or regular expression
Parameter value
value to match, e.g. a selector or a variable name
Modifiers
@public
function mergeExtractorSelectors
mergeExtractorSelectors: ( ...extractors: (ExtractorResultDetailed | ExtractorResultSets)[]) => ExtractorResultSets;Merge two extractor selectors
Parameter extractorSelectorsA
extractor selectors A
Parameter extractorSelectorsB
extractor selectors B
Returns
the merged extractor result sets
Modifiers
@public
function setOptions
setOptions: (configFile?: string) => Promise<Options>;Load the configuration file from the path
Parameter configFile
Path of the config file
Returns
The options from the configuration file
Throws
Error This exception is thrown if the configuration file was not imported
Modifiers
@public
function standardizeSafelist
standardizeSafelist: ( userDefinedSafelist?: UserDefinedSafelist) => Required<ComplexSafelist>;Format the user defined safelist into a standardized safelist object
Parameter userDefinedSafelist
the user defined safelist
Returns
the formatted safelist object that can be used in the PurgeCSS options
Modifiers
@public
Classes
class ContentCache
class ContentCache {}Cache of the selectors extracted from content files, shared across PurgeCSS instances.
Integrations that run PurgeCSS many times with the same content, e.g. a PostCSS plugin called once per CSS file or a bundler plugin in watch mode, can set the same cache on every PurgeCSS instance they create with PurgeCSS.contentCache. A content file is then only read and extracted again when its modification time, change time, size, inode or the extractor used for it changed. Runs at the same time share the files being read and extracted: each file is extracted once.
A file modified or changed (e.g. its modification time set back) less than 2 seconds before it was read is extracted again on the next run, as a modification within the precision of the file system timestamps would keep the same modification and change times.
The paths given to the methods are resolved from the current working directory.
Globs are still resolved on every run, so new files are picked up and deleted files no longer contribute selectors. The entries of the files that are no longer used stay in the cache until ContentCache.prune, ContentCache.delete or ContentCache.clear is called.
The extractors are called concurrently and in no particular order: they must not depend on the order of the files or on a state kept between files.
Example 1
const contentCache = new ContentCache()for (const css of cssFiles) {const purgeCSS = new PurgeCSS()purgeCSS.contentCache = contentCacheawait purgeCSS.purge({ content: ['src/pages/*.html'], css: [css] })}Modifiers
@public
property size
readonly size: number;Number of files in the cache
method clear
clear: () => void;Remove all the files from the cache
method delete
delete: (filePath: string) => boolean;Remove a file from the cache
Parameter filePath
path of the content file
Returns
true if the file was in the cache
method get
get: ( filePath: string, stats: ContentFileStats, extractor: ExtractorFunction) => Promise<ExtractorResultSets> | undefined;Get the selectors of a file if they are still valid. The selectors may still be being extracted by another run.
Parameter filePath
path of the content file
Parameter stats
current stats of the file
Parameter extractor
extractor function used for the file
Returns
the selectors extracted from the file, or
undefinedwhen the file is not in the cache or changed since it was extracted
method has
has: (filePath: string) => boolean;Check if a file is in the cache, whether its entry is still valid or not
Parameter filePath
path of the content file
method keys
keys: () => IterableIterator<string>;Absolute paths of the files in the cache
method prune
prune: (filePaths: Iterable<string>) => number;Remove the files that are not in the given list, e.g. the files of a previous build that the content globs no longer match
Parameter filePaths
paths of the files to keep
Returns
the number of files removed
method set
set: (filePath: string, entry: ContentCacheEntry) => void;Store the selectors of a file. The entry is removed when its selectors reject, or once they resolve when the file was modified or changed less than 2 seconds before ContentCacheEntry.checkedAt.
Parameter filePath
path of the content file
Parameter entry
selectors of the file and what they were extracted from
class ExtractorResultSets
class ExtractorResultSets {}Modifiers
@public
constructor
constructor(er: ExtractorResult);method hasAttrName
hasAttrName: (name: string) => boolean;method hasAttrPrefix
hasAttrPrefix: (prefix: string) => boolean;method hasAttrSubstr
hasAttrSubstr: (substr: string) => boolean;method hasAttrSuffix
hasAttrSuffix: (suffix: string) => boolean;method hasAttrValue
hasAttrValue: (value: string) => boolean;method hasClass
hasClass: (name: string) => boolean;method hasId
hasId: (id: string) => boolean;method hasTag
hasTag: (tag: string) => boolean;method merge
merge: (that: ExtractorResult | ExtractorResultSets) => this;class PurgeCSS
class PurgeCSS {}Class used to instantiate PurgeCSS and can then be used to purge CSS files.
Example 1
await new PurgeCSS().purge({content: ['index.html'],css: ['css/app.css']})Modifiers
@public
property contentCache
contentCache?: ContentCache;Cache of the selectors extracted from the content files. When set, a content file is only read and extracted again if it changed since the cache got its selectors, see ContentCache. The same cache can be set on several PurgeCSS instances, running one after the other or at the same time.
property options
options: Options;property removedNodes
removedNodes: postcss.Node[];property selectorsRemoved
selectorsRemoved: Set<string>;property variablesStructure
variablesStructure: VariablesStructure;method extractSelectorsFromFiles
extractSelectorsFromFiles: ( files: string[], extractors: Extractors[]) => Promise<ExtractorResultSets>;Extract the selectors present in the files using a PurgeCSS extractor
Parameter files
Array of files path or glob pattern
Parameter extractors
Array of extractors
method extractSelectorsFromString
extractSelectorsFromString: ( content: RawContent[], extractors: Extractors[]) => Promise<ExtractorResultSets>;Extract the selectors present in the passed string using a PurgeCSS extractor
Parameter content
Array of content
Parameter extractors
Array of extractors
method getPurgedCSS
getPurgedCSS: ( cssOptions: Array<string | RawCSS>, selectors: ExtractorResultSets) => Promise<ResultPurge[]>;Get the purged version of the css based on the files
Parameter cssOptions
css options, files or raw strings
Parameter selectors
set of extracted css selectors
method purge
purge: ( userOptions: UserDefinedOptions | string | undefined) => Promise<ResultPurge[]>;Remove unused CSS
Parameter userOptions
PurgeCSS options or path to the configuration file
Returns
an array of object containing the filename and the associated CSS
Example 1
Using a configuration file named purgecss.config.js
const purgeCSSResults = await new PurgeCSS().purge()Example 2
Using a custom path to the configuration file
const purgeCSSResults = await new PurgeCSS().purge('./purgecss.config.js')Example 3
Using the PurgeCSS options
const purgeCSSResults = await new PurgeCSS().purge({content: ['index.html', '**\/*.js', '**\/*.html', '**\/*.vue'],css: ['css/app.css']})
method removeUnusedCSSVariables
removeUnusedCSSVariables: () => void;Remove unused CSS variables
method removeUnusedFontFaces
removeUnusedFontFaces: () => void;Remove unused font-faces
method removeUnusedKeyframes
removeUnusedKeyframes: () => void;Remove unused keyframes
method walkThroughCSS
walkThroughCSS: (root: postcss.Root, selectors: ExtractorResultSets) => void;Walk through the CSS AST and remove unused CSS
Parameter root
root node of the postcss AST
Parameter selectors
selectors used in content files
class VariableNode
class VariableNode {}Modifiers
@public
constructor
constructor(declaration: postcss.Declaration);property isUsed
isUsed: boolean;property nodes
nodes: VariableNode[];Deprecated
The dependencies between declarations are no longer recorded, so this list is always empty. The variables used by a used variable are found by name in
VariablesStructure.removeUnused. It will be removed in the next major version.
property value
value: postcss.Declaration;class VariablesStructure
class VariablesStructure {}Modifiers
@public
property nodes
nodes: Map<string, VariableNode[]>;property properties
properties: Map<string, postcss.AtRule[]>;property safelist
safelist: StringRegExpArray;property usedVariables
usedVariables: Set<string>;method addProperty
addProperty: (atRule: postcss.AtRule) => void;Register an
@propertyat-rule so it can be removed along with the declarations of the variable it definesParameter atRule
@propertyat-rule
method addVariable
addVariable: (declaration: postcss.Declaration) => void;method addVariableUsage
addVariableUsage: ( declaration: postcss.Declaration, matchedVariables: IterableIterator<RegExpMatchArray>) => void;Deprecated
The variables used by a custom property are found by name in
removeUnused, so the dependencies between declarations are no longer recorded and this method does nothing. It will be removed in the next major version.
method addVariableUsageInProperties
addVariableUsageInProperties: ( matchedVariables: IterableIterator<RegExpMatchArray>) => void;method isVariablesSafelisted
isVariablesSafelisted: (variable: string) => boolean;method removeUnused
removeUnused: () => void;method setAsUsed
setAsUsed: (variableName: string) => void;Mark every declaration of the variable as used. The variables it uses are not marked,
removeUnusedadds them to the used variables first.Parameter variableName
name of the variable, e.g.
--color
Interfaces
interface ContentCacheEntry
interface ContentCacheEntry extends ContentFileStats {}Selectors extracted from a content file, along with what they were extracted from
Modifiers
@public
property checkedAt
checkedAt: number;time,
Date.now(), right before the file was stat. When the file was modified or changed less than 2 seconds before, the entry is only shared while the file is being read and extracted, and is removed once it is done.
property extractor
extractor: ExtractorFunction;extractor function used to extract the selectors
property selectors
selectors: Promise<ExtractorResultSets>;selectors extracted from the file. The promise is stored as soon as the file starts being read, so that runs at the same time share the work.
interface ContentFileStats
interface ContentFileStats {}Information of
fs.Statsthat tells if a content file changedModifiers
@public
property ctimeMs
ctimeMs: number;change time of the file,
fs.Stats.ctimeMs. Unlike the modification time, it cannot be set back, e.g. bytouch -ror a backup restore.
property ino
ino: number;inode number of the file,
fs.Stats.ino
property mtimeMs
mtimeMs: number;modification time of the file,
fs.Stats.mtimeMs
property size
size: number;size of the file in bytes,
fs.Stats.size
interface ExtractorResultDetailed
interface ExtractorResultDetailed {}Modifiers
@public
property attributes
attributes: { names: string[]; values: string[];};property classes
classes: string[];property ids
ids: string[];property tags
tags: string[];property undetermined
undetermined: string[];interface Extractors
interface Extractors {}Modifiers
@public
property extensions
extensions: string[];property extractor
extractor: ExtractorFunction;interface Options
interface Options {}Options used by PurgeCSS to remove unused CSS Those options are used internally
See Also
UserDefinedOptions for the options defined by the user
Modifiers
@public
property blocklist
blocklist: StringRegExpArray;Blocklist will block the CSS selectors from appearing in the final output CSS. The selectors will be removed even when they are seen as used by PurgeCSS.
property content
content: Array<string | RawContent>;You can specify content that should be analyzed by PurgeCSS with an array of filenames or globs. The files can be HTML, Pug, Blade, etc.
Example 1
await new PurgeCSS().purge({content: ['index.html', '*.js', '*.html', '*.vue'],css: ['css/app.css']})Example 2
PurgeCSS also works with raw content. To do this, you need to pass an object with the
rawproperty instead of a filename. To work properly with custom extractors you need to pass theextensionproperty along with the raw content.await new PurgeCSS().purge({content: [{raw: '<html><body><div class="app"></div></body></html>',extension: 'html'},'*.js','*.html','*.vue'],css: [{raw: 'body { margin: 0 }'},'css/app.css']})
property css
css: Array<string | RawCSS>;Similar to content, you can specify css that should be processed by PurgeCSS with an array of filenames or globs
property defaultExtractor
defaultExtractor: ExtractorFunction;property dynamicAttributes
dynamicAttributes: StringRegExpArray;Attributes that are set or changed at runtime, e.g. by JavaScript, and therefore may not appear in the content files. Attribute selectors on these attributes are kept whatever their value. Strings match the attribute name exactly, regular expressions are tested against it.
Example 1
await new PurgeCSS().purge({content: ['index.html'],css: ['css/app.css'],dynamicAttributes: ['aria-selected', /^data-/]})
property extractors
extractors: Array<Extractors>;property fontFace
fontFace: boolean;If there are any unused @font-face rules in your css, you can remove them by setting the
fontFaceoption totrue.Example 1
await new PurgeCSS().purge({content: ['index.html', '*.js', '*.html', '*.vue'],css: ['css/app.css'],fontFace: true})
property keyframes
keyframes: boolean;property output
output?: string;property rejected
rejected: boolean;property rejectedCss
rejectedCss: boolean;property safelist
safelist: Required<ComplexSafelist>;You can indicate which selectors are safe to leave in the final CSS. This can be accomplished with the option safelist.
property skippedContentGlobs
skippedContentGlobs: Array<string>;If you provide globs for the content parameter, you can use this option to exclude certain files or folders that would otherwise be scanned. Pass an array of globs matching items that should be excluded. (Note: this option has no effect if content is not globs.)
property sourceMap
sourceMap: | boolean | (postcss.SourceMapOptions & { to?: string; });See documentation for SourceMapOptions from package postcss.
property stdin
stdin: boolean;property stdout
stdout: boolean;property variables
variables: boolean;interface RawContent
interface RawContent<T = string> {}Modifiers
@public
interface RawCSS
interface RawCSS {}Modifiers
@public
interface ResultPurge
interface ResultPurge {}Modifiers
@public
property css
css: string;property file
file?: string;property rejected
rejected?: string[];property rejectedCss
rejectedCss?: string;property sourceMap
sourceMap?: string;sourceMap property will be empty if UserDefinedOptions.sourceMap inline is not set to false, as the source map will be contained within the text of ResultPurge.css
interface UserDefinedOptions
interface UserDefinedOptions {}Options used by PurgeCSS to remove unused CSS
Modifiers
@public
property blocklist
blocklist?: StringRegExpArray;See documentation for Options.blocklist from package purgecss.
property content
content: Array<string | RawContent>;See documentation for Options.content from package purgecss.
property css
css: Array<string | RawCSS>;See documentation for Options.css from package purgecss.
property defaultExtractor
defaultExtractor?: ExtractorFunction;See documentation for Options.defaultExtractor from package purgecss.
property dynamicAttributes
dynamicAttributes?: StringRegExpArray;See documentation for Options.dynamicAttributes from package purgecss.
property extractors
extractors?: Array<Extractors>;See documentation for Options.extractors from package purgecss.
property fontFace
fontFace?: boolean;See documentation for Options.fontFace from package purgecss.
property keyframes
keyframes?: boolean;See documentation for Options.keyframes from package purgecss.
property output
output?: string;See documentation for Options.output from package purgecss.
property rejected
rejected?: boolean;See documentation for Options.rejected from package purgecss.
property rejectedCss
rejectedCss?: boolean;See documentation for Options.rejectedCss from package purgecss.
property safelist
safelist?: UserDefinedSafelist;See documentation for Options.safelist from package purgecss.
property skippedContentGlobs
skippedContentGlobs?: Array<string>;See documentation for Options.skippedContentGlobs from package purgecss.
property sourceMap
sourceMap?: | boolean | (postcss.SourceMapOptions & { to?: string; });See documentation for Options.sourceMap from package purgecss.
property stdin
stdin?: boolean;See documentation for Options.stdin from package purgecss.
property stdout
stdout?: boolean;See documentation for Options.stdout from package purgecss.
property variables
variables?: boolean;See documentation for Options.variables from package purgecss.
Type Aliases
type ComplexSafelist
type ComplexSafelist = { standard?: StringRegExpArray; /** * You can safelist selectors and their children based on a regular * expression with `safelist.deep` * * @example * * ```ts * const purgecss = await new PurgeCSS().purge({ * content: [], * css: [], * safelist: { * deep: [/red$/] * } * }) * ``` * * In this example, selectors such as `.bg-red .child-of-bg` will be left * in the final CSS, even if `child-of-bg` is not found. * */ deep?: StringRegExpArray; /** * You can safelist whole selectors if any part of that selector matches a * pattern with `safelist.greedy` * * @example * * ```ts * const purgecss = await new PurgeCSS().purge({ * content: [], * css: [], * safelist: { * greedy: [/red$/] * } * }) * ``` * * In this example, selectors such as `button.bg-red.nonexistent-class` * will be left in the final CSS, even if `button` and `nonexistent-class` * are not found. * */ greedy?: StringRegExpArray; variables?: StringRegExpArray; keyframes?: StringRegExpArray;};Modifiers
@public
type ExtractorFunction
type ExtractorFunction<T = string> = (content: T) => ExtractorResult;Modifiers
@public
type ExtractorResult
type ExtractorResult = ExtractorResultDetailed | string[];Modifiers
@public
type PostCSSRoot
type PostCSSRoot = postcss.Root;Modifiers
@public
type StringRegExpArray
type StringRegExpArray = Array<RegExp | string>;Strings and regular expressions an option is matched against. A string matches a value exactly, except a string written between slashes, like
"/^btn-/"or"/^btn-/i", which is parsed as a regular expression. This form lets configuration files that cannot contain regular expressions, such aspostcss.config.json, use patterns.Modifiers
@public
type UserDefinedSafelist
type UserDefinedSafelist = StringRegExpArray | ComplexSafelist;Modifiers
@public
Package Files (1)
Dependencies (4)
Dev Dependencies (1)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/purgecss.
- Markdown[](https://www.jsdocs.io/package/purgecss)
- HTML<a href="https://www.jsdocs.io/package/purgecss"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 4576 ms. - Missing or incorrect documentation? Open an issue for this package.
