Skip to content

$1, $& in string replacements for RegExp find are not expanded #117

Open

Description

@trackoor

Describe the bug

The README for options.values states: "If it's a string, it will replace the substring matched by pattern. A number of special replacement patterns are supported". However, transform passes string replacements through String(ensureFunction(finalReplacement)(id, match)), which returns the string verbatim without expanding $1, $&, $<name>, or $$.

// repro.mjs
import Replace from 'unplugin-replace/rollup'

const plugin = Replace({
  values: [{ find: /process\.env\.(\w+)/g, replacement: 'import.meta.env.$1' }],
})

const res = await plugin.transform.handler.call(
  {},
  'f(process.env.API_URL)',
  '/src/a.js',
)
console.log(res.code)

Running node repro.mjs:

Actual output:

f(import.meta.env.$1)

Expected output (as with String.prototype.replace):

f(import.meta.env.API_URL)

Reproduction

https://gist.github.com/trackoor/f81e40bdea191f6e323b0e544f0f2cc3

System Info

System:
  OS: Linux 6.1 Debian GNU/Linux 12 (bookworm) 12 (bookworm)
  CPU: (64) x64 Intel(R) Xeon(R) CPU @ 2.80GHz
  Shell: 5.2.15 - /bin/bash
Binaries:
  Node: 26.13.0
  npm: 11.20.0
npmPackages:
  unplugin-replace: 0.9.1 (also tested on main 8d4c2e2)

Used Package Manager

npm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Credit: https://ucsbplse.github.io/

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions