evanw/esbuild

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

Opened this issue · 0 comments

jxn-30 commented

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