You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf: cache the config explorer, plugins and processor per compilation - #749
Supersedes #748 and keeps its commit (authored by @ptweezy) as the first commit, with them as co-author on the follow-up.
#748 reuses the cosmiconfig explorer for all files of a compilation. Every CSS file was searching for and evaluating the PostCSS config again. This PR builds on it:
A generic per-compilation cache: src/compilation-cache.js.createCompilationCache() returns a cache with get(loaderContext, keys, factory), has and delete. Values are stored per loaderContext._compilation and per list of keys:
Object and function keys are compared by identity and held in WeakMaps, so cached values are freed together with their compilation. Primitive keys are compared by value.
A new compilation (for example a watch rebuild) starts empty, so config changes are picked up.
Without a compilation (direct calls, or thread-loader, which passes a new stub context for every file), nothing is cached.
If the factory throws or returns a rejected promise, nothing is kept: the error is reported for every file and the next call tries again.
The module contains no PostCSS code, so other loaders that load configuration (sass-loader, less-loader and others) can use the same approach. It could later move to a shared package.
Config explorer. It now uses the helper, and its search places and loaders are built only when an explorer is created, not for every file.
Resolved plugins. These are cached per compilation, config object and loader options. Before, plugins given by name ({ "postcss-short": {} } or [["x", opts]]) were required and instantiated for every file.
A function config or function postcssOptions returns a new object for every file, so its plugins are still created for every file.
A plugin that fails to load is still reported for every file.
The PostCSS Processor. It is reused for files with the same implementation and plugins. A processor only holds its normalized plugins, and every process() call creates a new LazyResult.
Windows CI fix. The config-cache tests failed on windows-latest. The temporary projects were created in os.tmpdir(), which can be on another drive (C:) than the checkout (D:). The module ids then became absolute paths, and getCodeFromBundle reached a runtime module and threw Module.id: There was no ChunkGraph assigned…. The tests now compile each project with context set to the project itself, using realpathSync.native of the temporary directory.
Behavior note
Plugin instances are now created once per compilation, not once per file. This covers instances created in an object postcss.config.js (as in #748), plugins given by name in the config or the loader options, and plugin creators passed without being called (instantiated by the Processor). This already happens for ESM (.mjs) and TS configs, which Node and jiti cache for the whole process, and for plugin instances set in the loader options. postcss-cli, Vite and Next.js also load the config once. PostCSS 8 plugins keep per-file state in prepare() or the visitor handlers. Function configs and function postcssOptions still give per-file plugins, so that remains the way to opt out.
Benchmark
Whole compiler.run(), 1000 CSS files in 6 nested folders, cache: false, Node 22, Linux container, median of 5 runs (separate processes):
One or more co-authors of this pull request were not found. You must specify co-authors in commit message trailer via:
Co-authored-by: name <email>
Supported Co-authored-by: formats include:
Anything <id+login@users.noreply.github.com> - it will locate your GitHub user by id part.
Anything <login@users.noreply.github.com> - it will locate your GitHub user by login part.
Anything <public-email> - it will locate your GitHub user by public-email part. Note that this email must be made public on Github.
Anything <other-email> - it will locate your GitHub user by other-email part but only if that email was used before for any other CLA as a main commit author.
login <any-valid-email> - it will locate your GitHub user by login part, note that login part must be at least 3 characters long.
Alternatively, if the co-author should not be included, remove the Co-authored-by: line from the commit message.
Please update your commit message(s) by doing git commit --amend and then git push [--force] and then request re-running CLA check via commenting on this pull request:
❌ Patch coverage is 98.98990% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 90.09%. Comparing base (4b954cc) to head (c4fa1f5). ⚠️ Report is 1 commits behind head on main.
`loadConfig` created a cosmiconfig explorer per file, so its search and
load caches never hit. Every CSS file repeated the config search (27
places per directory, up to the home directory when there is no config
file), cosmiconfig's synchronous read of `package.json`, and the
evaluation of `postcss.config.js`.
Keep one explorer per compilation in a `WeakMap` keyed by
`loaderContext._compilation`. Each compilation gets a new explorer, so
config changes are still picked up in watch mode. Dependencies are still
added, and function configs still called, for every file. Without a
compilation object, behavior is unchanged.
As the loaded config is now shared, copy its map options before setting
`prev` on them.
Builds on the per-compilation config explorer:
- Add `src/compilation-cache.js`, a generic cache of values per webpack
compilation and list of keys (object keys held weakly, errors and
rejected promises not kept). It has no PostCSS-specific code, so other
loaders that load configuration can use the same approach.
- Use it for the cosmiconfig explorer, and build the explorer options
only when an explorer is created.
- Cache the resolved plugins per compilation, config object and loader
options. Plugins given by name (e.g. `{ "postcss-short": {} }`) are no
longer required and created for every file. A function config or
function `postcssOptions` still gets its plugins created for every
file, and a plugin that fails to load is still reported for every file.
- Reuse the PostCSS processor for files with the same plugins.
Fix the config cache tests on Windows: compile the temporary projects
with the project as the context, so module ids do not become absolute
paths when the temporary directory is on another drive.
Co-authored-by: Parker Loflin <parker@cronstable.dev>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FhutPPr1aX2Db4v3zBR34
No actionable comments were generated in the recent review.
Walkthrough
The change adds a compilation-scoped cache with support for primitive and identity-based keys, promise retry after rejection, and uncached operation when no compilation is available. PostCSS configuration explorers, resolved plugins, and processors now use compilation-scoped caching. Source-map processing copies map options before adding the previous map. New tests and fixtures cover cache behavior, configuration and plugin reuse, and source-map isolation.
Merge Risk: Minimal · up to c4fa1
The change caches the config explorer, resolved plugins and PostCSS processors per compilation. Function configs and function postcssOptions still resolve plugins for every file, and a function config's returned object is copied, so plugin lists from one file should not leak into another. No concrete merge-blocking risk remains after review.
Pre-merge checks: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
The title "perf: cache the config explorer, plugins and processor per compilation" matches the main change. The PR adds a compilation-scoped cache (src/compilation-cache.js) and uses it in src/utils.j…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title "perf: cache the config explorer, plugins and processor per compilation" matches the main change. The PR adds a compilation-scoped cache (src/compilation-cache.js) and uses it in src/utils.js for the PostCSS config explorer and plugin lists, and in src/index.js for PostCSS processors. The title is short, specific, and uses a conventional commit prefix. Function-based configs and postcssOptions remain per-file, which the title does not mention, but that is an expected detail and does not make the title misleading.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Warning
Some tools did not complete. Review the errors below.
ESLint
If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.
ESLint install timed out. The project may have too many dependencies for the sandbox.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: 2346c2fe-cb20-4a5a-9235-68ec8c7cf3b9
Commits
Reviewing files that changed from the base of the PR and between f67d161 and c4fa1f5.
Files selected for processing: 3
src/utils.js
test/compilation-cache.test.js
test/config-cache.test.js
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: bd13ca6f-6830-4eaa-b8d1-d9bbc2741020
Commits
Reviewing files that changed from the base of the PR and between 4b954cc and ddddde6.
Files selected for processing: 8
src/compilation-cache.js
src/index.js
src/utils.js
test/compilation-cache.test.js
test/config-cache.test.js
test/fixtures/config-cache/counting-plugin.js
test/fixtures/config-cache/map-loader.js
test/fixtures/config-cache/plugin.js
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
…tions`
A function config or function `postcssOptions` is called for every file
and can return the same object with other plugins, so caching the plugins
by the returned object gave later files the plugins of the first file.
Resolve their plugins for every file, as before.
Also copy the object a function config returns: the config module is now
loaded once per compilation, so the function can be called for other
files, and change the returned object, before the loader reads it.
Co-authored-by: Parker Loflin <parker@cronstable.dev>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FhutPPr1aX2Db4v3zBR34
Replace `standard-version` with Changesets and add a `release.yml`
workflow (changesets/action, npm OIDC trusted publishing) mirroring
webpack/less-loader. Add changesets for the unreleased #746 and #749.
Claude-Session: https://claude.ai/code/session_013FhutPvUFin2ATRcnG12Q1
Co-authored-by: Claude <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Supersedes #748 and keeps its commit (authored by @ptweezy) as the first commit, with them as co-author on the follow-up.
#748 reuses the cosmiconfig explorer for all files of a compilation. Every CSS file was searching for and evaluating the PostCSS config again. This PR builds on it:
A generic per-compilation cache:
src/compilation-cache.js.createCompilationCache()returns a cache withget(loaderContext, keys, factory),hasanddelete. Values are stored perloaderContext._compilationand per list of keys:WeakMaps, so cached values are freed together with their compilation. Primitive keys are compared by value.thread-loader, which passes a new stub context for every file), nothing is cached.The module contains no PostCSS code, so other loaders that load configuration (sass-loader, less-loader and others) can use the same approach. It could later move to a shared package.
Config explorer. It now uses the helper, and its search places and loaders are built only when an explorer is created, not for every file.
Resolved plugins. These are cached per compilation, config object and loader options. Before, plugins given by name (
{ "postcss-short": {} }or[["x", opts]]) wererequired and instantiated for every file.postcssOptionsreturns a new object for every file, so its plugins are still created for every file.The PostCSS
Processor. It is reused for files with the same implementation and plugins. A processor only holds its normalized plugins, and everyprocess()call creates a newLazyResult.Windows CI fix. The
config-cachetests failed onwindows-latest. The temporary projects were created inos.tmpdir(), which can be on another drive (C:) than the checkout (D:). The module ids then became absolute paths, andgetCodeFromBundlereached a runtime module and threwModule.id: There was no ChunkGraph assigned…. The tests now compile each project withcontextset to the project itself, usingrealpathSync.nativeof the temporary directory.Behavior note
Plugin instances are now created once per compilation, not once per file. This covers instances created in an object
postcss.config.js(as in #748), plugins given by name in the config or the loader options, and plugin creators passed without being called (instantiated by theProcessor). This already happens for ESM (.mjs) and TS configs, which Node and jiti cache for the whole process, and for plugin instances set in the loader options. postcss-cli, Vite and Next.js also load the config once. PostCSS 8 plugins keep per-file state inprepare()or the visitor handlers. Function configs and functionpostcssOptionsstill give per-file plugins, so that remains the way to opt out.Benchmark
Whole
compiler.run(), 1000 CSS files in 6 nested folders,cache: false, Node 22, Linux container, median of 5 runs (separate processes):postcss.config.jswith plugin instancespostcss.config.jswith plugins by namepostcss.config.jsconfig: false, plugins in loader optionsWith the PR, profiling shows the loader's own time is now mostly PostCSS processing. The config is loaded once per compilation.
What kind of change does this PR introduce?
perf
Did you add tests for your changes?
Yes.
test/compilation-cache.test.js: unit tests for the helper:delete.test/config-cache.test.js: everything from fix(perf): reuse the config explorer for all files of a compilation #748 (now also passing on Windows), plus:postcssOptionscreated for every file;implementation()call per compilation;Does this PR introduce a breaking change?
No API change. Plugin instances are shared within a build (see the behavior note).
If relevant, what needs to be documented once your changes are merged or what have you already documented?
Possibly a short README note that plugin instances are shared within a compilation, and that a function config is the way to get per-file plugins.
Generated by Claude Code
Summary by CodeRabbit
Improvements
Bug Fixes