Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Request: Allow passing regular expressions (RegExp) via define #4019

Open
jxn-30 opened this issue Dec 26, 2024 · 1 comment
Open

Comments

@jxn-30
Copy link

jxn-30 commented Dec 26, 2024

Currently, passing regular expressions via define is not possible. Passing a RegExp fails with Expected value for define "__MY_REGEXP__" to be a string, got object instead while passing a string representation (/my[rR]eg[eE]xp/gm.toString()) fails with Invalid define value (must be an entity name or valid JSON syntax): /my[rR]eg[eE]xp/gm

Current workaround:

// esbuild config
{
  // ...
  define: {
    __MY_REGEXP__: JSON.stringify(/my[rR]eg[eE]xp/gm.toString().replace(/^\/|\/[dgimsuvy]*$/g, '')),
    __MY_REGEXP_FLAGS__: JSON.stringify(/my[rR]eg[eE]xp/gm.flags),
  }
}
// index.js
const myRegExp = new RegExp(__MY_REGEXP__, __MY_REGEXP_FLAGS__);

// output
const myRegExp = new RegExp("my[rR]eg[eE]xp", "gm");

It would be nice to have this easier, so that this workaround is not required anymore:

// esbuild config
{
  // ...
  define: {
    __MY_REGEXP__: /my[rR]eg[eE]xp/gm,
  }
}
// index.js
const myRegExp = __MY_REGEXP__;

// output
const myRegExp = /my[rR]eg[eE]xp/gm;

// alternative output (replacement similar to objects and arrays)
let __MY_REGEXP__ = /my[rR]eg[eE]xp/gm;
const myRegExp = __MY_REGEXP__;

Passing a RegExp via CLI could be similar: --define:__MY_REGEXP__=/my[rR]eg[eE]xp/gm

@jxn-30 jxn-30 changed the title Feature Request: Allow passing regular expressions (RegExp) via define when using JS/TS config Feature Request: Allow passing regular expressions (RegExp) via define Dec 28, 2024
@evanw
Copy link
Owner

evanw commented Feb 3, 2025

I took a brief look at this. One reason that this isn't trivial is that esbuild now supports transforming unsupported regular expression literals into new RegExp() calls to avoid syntax errors in older engines. Adding this feature is going to be a little harder than I initially thought.

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

No branches or pull requests

2 participants