Skip to content

[Bug]: Context Replacement Plugin applies changes even when the regex fails to match #12656

@agneym

Description

@agneym

System Info

System:
OS: macOS 26.1
CPU: (14) arm64 Apple M4 Max
Memory: 166.86 MB / 36.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 24.12.0 - /Users/agneymenon/.local/share/mise/installs/node/24.12.0/bin/node
Yarn: 1.22.22 - /Users/agneymenon/.local/share/mise/installs/node/24.12.0/bin/yarn
npm: 11.6.2 - /Users/agneymenon/.local/share/mise/installs/node/24.12.0/bin/npm
pnpm: 10.26.2 - /Users/agneymenon/.local/share/mise/installs/node/24.12.0/bin/pnpm
bun: 1.3.2 - /Users/agneymenon/.bun/bin/bun
Watchman: 2025.05.26.00 - /opt/homebrew/bin/watchman
Browsers:
Chrome Canary: 145.0.7618.0
Safari: 26.1
npmPackages:
@rspack/cli: ^1.7.1 => 1.7.1
@rspack/core: ^1.7.1 => 1.7.1

Details

If ContextReplacementPlugin is added to a configuration, it applies changes to all contexts even if regex does not match.

For example,

plugins: [
   new ContextReplacementPlugin(
      /^components$/,
      new RegExp(`src/components/.*`),
    ),
]

else where:

// This will not work anymore.
const context = require.context("./assets");
console.log(context.keys());

Reproduce link

https://github.com/agneym/rspack-context-replacement-plugin-issue-reproduction

Reproduce Steps

The reproduction repository has two configurations:

  1. rspack.config.ts - minimal configuration
  2. rspack-with-ctx-plugin - same configuration as above with context replacement plugin

I have commited builds with both of these for easy reproduction:

  1. Normal build: https://github.com/agneym/rspack-context-replacement-plugin-issue-reproduction/blob/main/dist/main.js - Note that react.svg file is discovered from assets.
  2. Ctx replacement plugin build - https://github.com/agneym/rspack-context-replacement-plugin-issue-reproduction/blob/main/dist-with-ctx-plugin/main.js - Above file is no longer discovered.

You can also run development servers to check the console logs in browser:

  1. Normal dev server: pnpm run dev
  2. Context replacement plugin dev server: pnpm run dev:with-ctx-plugin

Metadata

Metadata

Assignees

No one assigned

    Labels

    pending triageThe issue/PR is currently untouched.

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions