Feature Request: Allow passing regular expressions (RegExp) via `define`
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
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.