Skip to content

perf: cache the config explorer, plugins and processor per compilation - #749

Merged
alexander-akait merged 4 commits into
mainfrom
claude/fervent-ptolemy-qatg12
Nov 20, 2026
Merged

alexander-akait merged 4 commits into
mainfrom
claude/fervent-ptolemy-qatg12

Conversation

@alexander-akait

@alexander-akait alexander-akait commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

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:

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

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

  3. 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.
  4. 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.

  5. 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):

setup main #748 this PR
postcss.config.js with plugin instances 5009 ms 1246 ms 1226 ms
postcss.config.js with plugins by name 5306 ms 1395 ms 1097 ms
function postcss.config.js 5319 ms ~1100–1250 ms ~1100–1250 ms (noise)
no config file, plugins in loader options 9685 ms 864 ms 878 ms
config: false, plugins in loader options 1116 ms 1111 ms 1075 ms

With 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:
    • values cached per compilation and keys;
    • identity vs value keys;
    • falsy values;
    • no compilation;
    • thrown errors and rejected promises not cached;
    • 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:
    • plugins of an object config, and named plugins in the loader options, created once per compilation and again for the next compilation;
    • plugins of a function config and of function postcssOptions created for every file;
    • one implementation() call per compilation;
    • a plugin that fails to load reported for every file.

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

    • PostCSS configuration and plugins are reused during a compilation, while updated configuration is picked up in subsequent compilations.
    • Function-based configuration and plugin options continue to be evaluated separately for each file.
  • Bug Fixes

    • Source map settings no longer carry over between files when processing multiple files.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

  • ✅ Unknown (e6497a3)
  • ✅ login: alexander-akait / name: Alexander Akait (e6497a3)
  • ✅ login: ptweezy / name: Parker Loflin (08d93ca, e6497a3)

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:

  1. Anything <id+login@users.noreply.github.com> - it will locate your GitHub user by id part.
  2. Anything <login@users.noreply.github.com> - it will locate your GitHub user by login part.
  3. Anything <public-email> - it will locate your GitHub user by public-email part. Note that this email must be made public on Github.
  4. 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.
  5. 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:

/easycla

@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
src/utils.js 97.43% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #749      +/-   ##
==========================================
+ Coverage   88.23%   90.09%   +1.85%     
==========================================
  Files           3        4       +1     
  Lines         357      434      +77     
  Branches      118      143      +25     
==========================================
+ Hits          315      391      +76     
- Misses         38       39       +1     
  Partials        4        4              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@alexander-akait
alexander-akait force-pushed the claude/fervent-ptolemy-qatg12 branch from ddddde6 to e6497a3 Compare November 20, 2026 13:04
ptweezy and others added 2 commits November 20, 2026 13:04
`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
@alexander-akait
alexander-akait force-pushed the claude/fervent-ptolemy-qatg12 branch from e6497a3 to f67d161 Compare November 20, 2026 13:04
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
@coderabbitai

coderabbitai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Explain Change →

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: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed 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 Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed 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.

Share

Recent 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: 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

Comment thread src/utils.js Resolved
…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
@alexander-akait
alexander-akait merged commit 7ee9cd0 into main Nov 20, 2026
19 checks passed
@alexander-akait
alexander-akait deleted the claude/fervent-ptolemy-qatg12 branch November 20, 2026 13:23
alexander-akait added a commit that referenced this pull request Nov 20, 2026
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants