UNPKG

purgecss-webpack-plugin

Version:

PurgeCSS plugin for webpack and Rspack - Remove unused css

678 lines (671 loc) • 28.3 kB
'use strict'; var fs = require('fs'); var path = require('path'); var url = require('url'); var purgecss = require('purgecss'); function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs); var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path); const stringLiteral = String.raw `"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'`; const identifier = String.raw `[A-Za-z_$][\w$]*`; /** * export of another module: `__webpack_require__("./a.css")["name"]`, * `__webpack_require__(378).h`, `e(378).h` once minimized */ const moduleReference = String.raw `${identifier}\(\s*(?:${stringLiteral}|\d+)\s*\)\s*(?:\[\s*(?:${stringLiteral})\s*\]|\.\s*${identifier})`; const moduleReferenceRegExp = new RegExp(String.raw `\(\s*(${stringLiteral}|\d+)\s*\)\s*(?:\[\s*(${stringLiteral})\s*\]|\.\s*(${identifier}))`); const term = String.raw `${stringLiteral}|${moduleReference}|${identifier}`; const termRegExp = new RegExp(term, "g"); // a string literal, or a concatenation of string literals, variables and // exports of other modules: Rspack generates `"a" + " " + "b"` for a class // that composes another one of the same file, and // `"a" + " " + __webpack_require__(id)["b"]` for a class of another file const stringLiterals = String.raw `(?:${term})(?:\s*\+\s*(?:${term}))*`; /** `var _1 = "class-name";`, `export const modUsed = "class-name";` */ const variableRegExp = new RegExp(String.raw `(\bexport\s+)?\b(?:var|let|const)\s+(${identifier})\s*=\s*(${stringLiterals})\s*(?=[;,\n]|$)`, "g"); /** `"modUsed": "class-name"`, `modUsed: _1` in an object literal */ const propertyRegExp = new RegExp(String.raw `[{,]\s*(${stringLiteral}|${identifier})\s*:\s*(${stringLiterals})\s*(?=[,}])`, "g"); /** `export { _1 as "modUsed", _2 as base }` */ const exportListRegExp = /\bexport\s*\{([^}]*)\}/g; const exportSpecifierRegExp = new RegExp(String.raw `^\s*(${identifier})(?:\s+as\s+(${stringLiteral}|${identifier}))?\s*$`); /** * Value of a JavaScript string literal * * @param literal - string literal, with its quotes */ function unquote(literal) { if (literal.startsWith('"')) { try { return JSON.parse(literal); } catch { // escapes that JSON does not have, e.g. `\'` } } return literal.slice(1, -1).replace(/\\(.)/g, "$1"); } /** * Class names and references to other modules of a value: a string literal, * a variable, the export of another module, or a concatenation of them * * @param value - JavaScript expression * @param variables - class names of the variables declared before * @returns the class names and references of the value, undefined when it * reads an unknown variable */ function getClassNames(value, variables) { let classes = ""; const references = []; for (const [part] of value.matchAll(termRegExp)) { if (/^["']/.test(part)) { classes += unquote(part); continue; } const reference = moduleReferenceRegExp.exec(part); if (reference) { const [, moduleId, quotedName, name] = reference; references.push({ moduleId: /^["']/.test(moduleId) ? unquote(moduleId) : moduleId, name: quotedName ? unquote(quotedName) : name, }); // a separate class list classes += " "; continue; } const variable = variables.get(part); if (!variable) return undefined; classes += ` ${variable.classNames.join(" ")} `; if (variable.references) references.push(...variable.references); } const classNames = classes.split(/\s+/).filter(Boolean); return references.length > 0 ? { classNames, references } : { classNames }; } /** * Read the export map of a CSS module from the JavaScript code that exports * it: the code generated by mini-css-extract-plugin and * `CssExtractRspackPlugin` (`export default {...}`, `module.exports = {...}`, * `var _1 = "..."; export { _1 as "name" }`) or by the native CSS support of * Rspack (`var exports = { "name": "a" + " " + "b" }`). With Rspack, a class * composed from another file is read from the export of the other module, * `"a" + " " + __webpack_require__("./b.module.css")["b"]`: the export lists * it in its `references`. * * The code is not parsed: it is only matched against the shapes these * plugins generate. Something else that looks like an export can only keep * more classes, as its class names are kept only when its name is found in * the content. * * @param source - JavaScript code of the module * @returns the exports of the CSS module */ function parseCssModuleExports(source) { const variables = new Map(); const cssExports = new Map(); const addExport = (key, value) => { const name = /^["']/.test(key) ? unquote(key) : key; cssExports.set(name, { ...value, name }); }; for (const [, isExported, name, value] of source.matchAll(variableRegExp)) { const classNames = getClassNames(value, variables); if (!classNames) continue; variables.set(name, { name, ...classNames }); if (isExported) addExport(name, classNames); } for (const [, key, value] of source.matchAll(propertyRegExp)) { const classNames = getClassNames(value, variables); if (classNames) addExport(key, classNames); } for (const [, specifiers] of source.matchAll(exportListRegExp)) { for (const specifier of specifiers.split(",")) { const match = exportSpecifierRegExp.exec(specifier); if (!match) continue; const [, local, exported = local] = match; const variable = variables.get(local); if (variable) addExport(exported, variable); } } return Array.from(cssExports.values()); } /** * Source code of a module as a string * * @param module - module with `originalSource` */ function getOriginalSource(module) { var _a, _b; const source = (_b = (_a = module === null || module === void 0 ? void 0 : module.originalSource) === null || _a === void 0 ? void 0 : _a.call(module)) === null || _b === void 0 ? void 0 : _b.source(); return source ? source.toString() : ""; } /** * JavaScript code generated for a module by the bundler, e.g. the export * map of a CSS module with the native CSS support of Rspack * * @param compilation - current compilation * @param module - module */ function getGeneratedJavaScript(compilation, module) { var _a, _b; const codeGenerationResults = compilation.codeGenerationResults; if (!codeGenerationResults) return ""; // Rspack takes no runtime when there is a single one, webpack takes the // runtime of a chunk of the module when there are several const runtimes = [undefined]; for (const chunk of compilation.chunkGraph.getModuleChunksIterable(module)) { runtimes.push(chunk.runtime); } for (const runtime of runtimes) { try { const result = codeGenerationResults.get(module, runtime); const source = (_b = (_a = result === null || result === void 0 ? void 0 : result.sources) === null || _a === void 0 ? void 0 : _a.get("javascript")) === null || _b === void 0 ? void 0 : _b.source(); if (source) return source.toString(); } catch { // no code generation result for this runtime } } return ""; } /** * Whether a module is a CSS module of the native CSS support of the bundler * * @param module - module */ function isNativeCss(module) { var _a; const type = (_a = module.type) !== null && _a !== void 0 ? _a : ""; return type === "css" || type.startsWith("css/"); } /** * Resolve the exports of other CSS modules that the exports of a module * refer to (classes composed from another file with Rspack): their class * names are added to the class names of the exports that refer to them. */ class ReferenceResolver { constructor(compilation) { this.compilation = compilation; /** exports of the modules, by module */ this.exportsByModule = new Map(); } /** * Exports of a native CSS module, read from its generated JavaScript code * * @param module - native CSS module */ getExports(module) { let cssExports = this.exportsByModule.get(module); if (!cssExports) { cssExports = parseCssModuleExports(getGeneratedJavaScript(this.compilation, module)); this.exportsByModule.set(module, cssExports); } return cssExports; } /** * Class names of an export and of the exports it refers to, recursively * * @param cssExport - export of a CSS module * @param visited - exports already resolved, against cycles */ resolve(cssExport, visited = new Set()) { var _a; visited.add(cssExport); const classNames = [...cssExport.classNames]; for (const reference of (_a = cssExport.references) !== null && _a !== void 0 ? _a : []) { const module = this.getModule(reference.moduleId); if (!module) continue; const moduleExports = this.getExports(module); const referenced = moduleExports.filter(({ name }) => name === reference.name); // an export that is not found keeps every class of the module rather // than removing a used class for (const target of referenced.length > 0 ? referenced : moduleExports) { if (!visited.has(target)) { classNames.push(...this.resolve(target, visited)); } } } return classNames; } /** * Native CSS module of an id * * @param moduleId - id of the module */ getModule(moduleId) { if (!this.modulesById) { this.modulesById = new Map(); const { chunkGraph } = this.compilation; for (const module of this.compilation.modules) { if (!isNativeCss(module)) continue; const id = chunkGraph.getModuleId(module); if (id !== null && id !== undefined) { this.modulesById.set(String(id), module); } } } return this.modulesById.get(moduleId); } } /** * Collect the export maps of the CSS modules of the chunks. * * - With mini-css-extract-plugin or `CssExtractRspackPlugin`, a CSS module is * a `css/mini-extract` module issued by a JavaScript module whose source is * the export map. * - With the native CSS support of webpack (`experiments.css`), the export map * is stored in the build info of the CSS module. * - With the native CSS support of Rspack (`css/auto`, `css/module`), the * export map is generated with the JavaScript code of the CSS module. When * `optimization.usedExports` is enabled, it only lists the exports used by * the JavaScript code, possibly under mangled names: they are all used. * The classes composed from another file are read from the export map of * the other module. * * @param compilation - current compilation * @param chunks - chunks whose CSS is purged * @returns the exports of the CSS modules of the chunks */ function collectCssModulesExports(compilation, chunks) { var _a, _b; const result = { exports: [], usedClassNames: [] }; const seen = new Set(); const seenStubs = new Set(); const usedExportsOnly = !!((_a = compilation.options.optimization) === null || _a === void 0 ? void 0 : _a.usedExports); const references = new ReferenceResolver(compilation); // Rspack 1.0 has no module graph in its JavaScript API: the module that // issues an extracted CSS module, its export map, cannot be found const moduleGraph = compilation.moduleGraph; for (const chunk of chunks) { for (const module of compilation.chunkGraph.getChunkModulesIterable(chunk)) { if (seen.has(module)) continue; seen.add(module); if (module.type === "css/mini-extract") { const stub = moduleGraph === null || moduleGraph === void 0 ? void 0 : moduleGraph.getIssuer(module); if (!stub || seenStubs.has(stub)) continue; seenStubs.add(stub); result.exports.push(...parseCssModuleExports(getOriginalSource(stub))); continue; } if (!isNativeCss(module)) continue; const cssData = (_b = module.buildInfo) === null || _b === void 0 ? void 0 : _b.cssData; if ((cssData === null || cssData === void 0 ? void 0 : cssData.exports) instanceof Map) { for (const [name, value] of cssData.exports) { result.exports.push({ name, classNames: value.split(/\s+/).filter(Boolean), }); } continue; } for (const cssExport of references.getExports(module)) { const classNames = references.resolve(cssExport); if (usedExportsOnly) { result.usedClassNames.push(...classNames); } else { result.exports.push({ name: cssExport.name, classNames }); } } } } return result; } const styleExtensions = [".css", ".scss", ".styl", ".sass", ".less"]; const pluginName = "PurgeCSS"; /** * Get the filename without ?hash * * @param fileName - file name */ function getFormattedFilename(fileName) { if (fileName.includes("?")) { return fileName.split("?").slice(0, -1).join(""); } return fileName; } /** * Returns true if the filename is of types of one of the specified extensions * * @param filename - file name * @param extensions - extensions */ function isFileOfTypes(filename, extensions) { const extension = path__namespace.extname(getFormattedFilename(filename)); return extensions.includes(extension); } /** * Options of PurgeCSS from the options of the plugin, without the content * and the css * * @param pluginOptions - options of the plugin * @param sourceMap - whether source maps are generated */ function getPurgeCSSOptions(pluginOptions, sourceMap) { const options = { ...purgecss.defaultOptions, ...pluginOptions, }; if (typeof options.safelist === "function") { options.safelist = options.safelist(); } if (typeof options.blocklist === "function") { options.blocklist = options.blocklist(); } return { defaultExtractor: options.defaultExtractor, extractors: options.extractors, fontFace: options.fontFace, keyframes: options.keyframes, output: options.output, rejected: options.rejected, variables: options.variables, safelist: options.safelist, blocklist: options.blocklist, dynamicAttributes: options.dynamicAttributes, // the source map of an asset is extracted by webpack (`devtool`), which // adds its own annotation. Its path defaults to the name of the asset. sourceMap: sourceMap ? { inline: false, annotation: false } : false, }; } /** * Create a PurgeCSS instance with its options set, without content or css * * @param options - options of PurgeCSS */ async function createPurgeCSS(options) { const purgeCSS = new purgecss.PurgeCSS(); // `purge` sets the options (default values, safelist) and has nothing to // read or purge await purgeCSS.purge({ ...options, content: [], css: [] }); return purgeCSS; } /** * Create the Source instance result of PurgeCSS * * @param webpackSources - `sources` of the bundler, webpack or Rspack * @param name - asset name * @param asset - webpack asset * @param purgeResult - result of PurgeCSS purge method * @param sourceMap - wether sourceMap is enabled * @returns the new Source */ function createSource(webpackSources, name, asset, purgeResult, sourceMap) { var _a, _b; if (!sourceMap || !purgeResult.sourceMap) { return new webpackSources.RawSource(purgeResult.css); } const { source, map } = asset.sourceAndMap(); const purgedMap = JSON.parse(purgeResult.sourceMap); // the map of the purged css points to the css before purging, under the // name in its `sources`, which the map of that css is applied to. What the // map of that css does not map, e.g. the comments added by // mini-css-extract-plugin, is left unmapped instead of being mapped to the // css before purging. return new webpackSources.SourceMapSource(purgeResult.css, (_b = (_a = purgedMap.sources) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : name, purgeResult.sourceMap, source.toString(), map !== null && map !== void 0 ? map : undefined, !!map); } /** * Add the content files to the dependencies of the compilation, so that the * watcher of webpack or Rspack runs a new compilation when one of them * changes, and return the files that do not exist. * * The watchers do not follow symbolic links by default * (`watchOptions.followSymlinks`): the target of a symbolic link, e.g. a * file of a workspace package linked in `node_modules`, is added too. * * @param compilation - compilation of webpack or Rspack * @param entryPaths - content files * @returns the content files that do not exist */ function addContentDependencies(compilation, entryPaths) { const missingPaths = []; for (const p of entryPaths) { const absolutePath = path__namespace.resolve(p); if (!fs__namespace.existsSync(absolutePath)) { missingPaths.push(p); compilation.missingDependencies.add(absolutePath); continue; } compilation.fileDependencies.add(absolutePath); const realPath = fs__namespace.realpathSync(absolutePath); if (realPath !== absolutePath) compilation.fileDependencies.add(realPath); } return missingPaths; } /** * @public */ class PurgeCSSPlugin { constructor(options) { this.purgedStats = {}; /** * Selectors extracted from the content files, kept from one compilation to * the next one in watch mode: only the files that changed are read again */ this.contentCache = new purgecss.ContentCache(); this.options = options; } /** * Apply the plugin to a webpack or Rspack compiler * * @param compiler - compiler of webpack or Rspack */ apply(compiler) { compiler.hooks.compilation.tap(pluginName, (compilation) => this.initializePlugin(compilation)); } /** * Purge the CSS assets of a compilation of webpack or Rspack * * @param compilationLike - compilation of webpack or Rspack */ initializePlugin(compilationLike) { const compilation = compilationLike; const { Compilation } = compilation.compiler.webpack; compilation.hooks.processAssets.tapPromise({ name: pluginName, // the stage of the deprecated `additionalAssets` hook the plugin used // to run in: the CSS assets of the chunks are added when the chunks // are rendered, before `processAssets`. Plugins that derive assets // from the CSS (PRE_PROCESS, DERIVED, ADDITIONS) read the purged CSS, // which is purged before it is minimized (OPTIMIZE_SIZE), its source // map extracted (DEV_TOOLING) and content hashes updated // (OPTIMIZE_HASH) stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, }, async () => { let configFileOptions; const t = path__namespace.resolve(process.cwd(), "purgecss.config.js"); // the config file is optional, but an existing one that fails to load // (e.g. a syntax error) is reported instead of being silently ignored if (fs__namespace.existsSync(t)) { try { const importedConfig = await import(url.pathToFileURL(t).href); // Handle both ES modules (direct export) and CommonJS (default export) configFileOptions = importedConfig.default && typeof importedConfig.default === "object" ? importedConfig.default : importedConfig; } catch (err) { throw new Error(`Error loading the config file ${t}: ${err}`, { cause: err, }); } } this.options = { ...(configFileOptions ? configFileOptions : {}), ...this.options, }; const entryPaths = typeof this.options.paths === "function" ? this.options.paths() : this.options.paths; // in watch mode, a change to a content file triggers a new // compilation, the content files being outside the module graph. A // missing file is watched too, so that the compilation runs again // once it is created. const missingPaths = addContentDependencies(compilation, entryPaths); if (missingPaths.length > 0) { // an error of the compilation, not of the hook: webpack watches // the dependencies of a compilation that failed with errors, not // of one whose hook threw const { WebpackError } = compilation.compiler.webpack; for (const p of missingPaths) { compilation.errors.push(new WebpackError(`Path ${p} does not exist.`)); } return; } return this.runPluginHook(compilation, entryPaths); }); } /** * Purge the CSS assets of a compilation * * @param compilationLike - compilation of webpack or Rspack * @param entryPaths - content files */ async runPluginHook(compilationLike, entryPaths) { var _a; const compilation = compilationLike; // CSS assets to purge, and the chunks they belong to. An asset of // several chunks is purged once. const assetsToPurge = new Set(); const chunksToPurge = new Set(); for (const chunk of compilation.chunks) { // `only` lists chunk names, e.g. the entry names. Compare them with the // chunk name, not with the asset path: a substring of the path also // matches other chunks (`style` in `style_print.css` or `css/style/`) if (this.options.only && !(chunk.name && this.options.only.includes(chunk.name))) { continue; } for (const name of chunk.files) { if (isFileOfTypes(name, [".css"]) && compilation.getAsset(name) && !assetsToPurge.has(name)) { assetsToPurge.add(name); chunksToPurge.add(chunk); } } } if (assetsToPurge.size === 0) return; const sourceMapEnabled = !!compilation.compiler.options.devtool; const purgeCSSOptions = getPurgeCSSOptions(this.options, sourceMapEnabled); // the content is extracted once for all the assets of the compilation const filesToSearch = entryPaths.filter((v) => !styleExtensions.some((ext) => v.endsWith(ext))); const contentPurgeCSS = await createPurgeCSS(purgeCSSOptions); contentPurgeCSS.contentCache = this.contentCache; const selectors = await contentPurgeCSS.extractSelectorsFromFiles(filesToSearch, contentPurgeCSS.options.extractors); // forget the files that are no longer part of the content this.contentCache.prune(filesToSearch); addCssModulesSelectors(selectors, collectCssModulesExports(compilation, chunksToPurge)); const webpackSources = compilation.compiler.webpack.sources; for (const name of assetsToPurge) { const asset = compilation.getAsset(name); if (!asset) continue; // an instance per asset: the font faces, keyframes and variables of an // asset are removed when unused in that asset const purgeCSS = await createPurgeCSS(purgeCSSOptions); // the asset name is the path of the css in the source map const [purged] = await purgeCSS.getPurgedCSS([{ raw: asset.source.source().toString(), name }], selectors); if (purged.rejected) { this.purgedStats[name] = purged.rejected; } // Rspack only writes the assets whose version changed since the // previous compilation, in watch mode: the version of the asset it // rendered does not change with the content files const hash = compilation.compiler.webpack.util.createHash((_a = compilation.outputOptions.hashFunction) !== null && _a !== void 0 ? _a : "xxhash64"); hash.update(purged.css); if (purged.sourceMap) hash.update(purged.sourceMap); const version = hash.digest("hex").toString(); compilation.updateAsset(name, createSource(webpackSources, name, asset.source, purged, sourceMapEnabled), (info) => ({ ...info, version })); } } } /** * Words of the selectors found in the content, for extractors that do not * split `styles.modUsed` into `styles` and `modUsed`, such as the extractors * of Tailwind CSS, which yield the token `styles.modUsed`. The selectors * are read from the sets of `ExtractorResultSets`; none are read if its * implementation changes. * * @param selectors - selectors found in the content */ function getContentWords(selectors) { const words = new Set(); const { classes, undetermined } = selectors; for (const tokens of [classes, undetermined]) { if (!(tokens instanceof Set)) continue; for (const token of tokens) { if (typeof token !== "string") continue; for (const word of token.split(/[^\w$-]+/)) { if (word) words.add(word); } } } return words; } /** * Add to the selectors found in the content the hashed class names of the * CSS modules that are used: those exported under a name found in the * content (`styles.modUsed` keeps the class exported as `modUsed`), and * those the bundler found to be used. * * @param selectors - selectors found in the content * @param cssModules - exports of the CSS modules */ function addCssModulesSelectors(selectors, cssModules) { const classNames = [...cssModules.usedClassNames]; let words; for (const { name, classNames: exported } of cssModules.exports) { if (selectors.hasClass(name)) { classNames.push(...exported); continue; } words !== null && words !== void 0 ? words : (words = getContentWords(selectors)); if (words.has(name)) classNames.push(...exported); } if (classNames.length > 0) { selectors.merge({ classes: classNames, ids: [], tags: [], attributes: { names: [], values: [] }, undetermined: [], }); } } exports.PurgeCSSPlugin = PurgeCSSPlugin;