babel-plugin-transform-regex v6.0.1
babel-plugin-transform-regex
This is a Babel plugin that transpiles tagged Regex+ regex templates into native RegExp literals, enabling syntax for modern and more readable regex features (atomic groups, subroutines, insignificant whitespace, comments, etc.) without the need for calling regex at runtime. Although Regex+ is already a lightweight and high-performance library, this takes things further by giving you its developer experience benefits without adding any runtime dependencies and without users paying any runtime cost.
Try the demo REPL
Example
Input:
const ipv4 = regex`
^ \g<byte> (\.\g<byte>){3} $
(?(DEFINE)
(?<byte> 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d)
)
`;Output:
const ipv4 = /^(?:2[0-4]\d|25[0-5]|1\d\d|[1-9]?\d)(?:\.(?:2[0-4]\d|25[0-5]|1\d\d|[1-9]?\d)){3}$/v;Supported
The following call formats are all supported:
regex`<expression>`regex()`<expression>`regex('<flags>')`<expression>`regex({<options>})`<expression>`
Interpolation into the expression is supported, so long as the interpolated values are:
- Inline string, regexp, or number literals.
- Inline regexes constructed via
RegExpornew RegExpwith string values. - Inline patterns, via
pattern`…`as a template tag (without interpolation) orpattern(…)as a function call with a string or number literal as the value.
Additional details:
- Wherever strings are allowed,
'…',"…",`…`, andString.raw`…`can all be used, so long as they don't include interpolation.
Unsupported
- Tagged
regextemplates that interpolate variables or other dynamic values are not transformed. - The specific
regexoptionssubclass,plugins, andunicodeSetsPluginare unsupported. Regexes that use these options are not transformed. - Calling the
regextag as a function instead of with backticks is not transformed.
Babel plugin options
The following options are available when running the Babel plugin:
removeImport— Iftrue, removes any import declarations with module name'regex'.disableUnicodeSets— Iftrue, addsregexoptiondisable: {v: true}to all regexes before transformation.headerComment— If given a value, it will be added in a comment at the top of processed output/files.optimize(experimental) — Iftrue, attempts to optimize/shorten the regex source generated byregex.- Uses an external library (regexp-tree's optimizer) that doesn't support flag-v-only syntax and isn't fully context-aware, so you should check the output.
Compatibility
By default, the regex tag implicitly adds flag v (unicodeSets, supported by Node.js 20 and 2023-era browsers) to generated regexes, but it automatically switches to flag u (while applying v's escaping rules) in environments without native v support. This creates an issue for the Babel plugin, because although it will typically be run in environments that support flag v, the transpiled results may need to run for users in old browsers without native v.
There are several ways to address this:
- Option 1: Leave v enabled and transpile v with a separate Babel plugin.
- This allows supporting v-only syntax (like nested character classes) in older environments.
- Use Babel's official plugin @babel/plugin-transform-unicode-sets-regex, which is also included in @babel/preset-env.
- Option 2: Disable v for all transpiled regexes.
- To do this, set the Babel plugin option
disableUnicodeSets: true(see details above). - This keeps things simple/clean and avoids a second regex transpilation step.
- This doesn't support the use of v-only syntax.
- To do this, set the Babel plugin option
- Option 3: Disable v for individual regexes.
- To do this, use the
regexoptionregex({disable: {v: true}})`…`in your code. - This maintains 100% parity between code running with or without the Babel plugin.
- This doesn't support the use of v-only syntax.
- To do this, use the
You can try all of these options in the demo REPL.
Installation and usage
Add this plugin and a recent version of Babel (tested with 7.24–7.26) to your project:
npm install --save-dev @babel/core @babel/cli
npm install --save-dev babel-plugin-transform-regexRun the following command to compile all of your code from the src directory to lib:
./node_modules/.bin/babel src --out-dir lib --plugins=babel-plugin-transform-regexOptional setup steps
To make this easier to run, create a config file in the root of your project named babel.config.json, with this content:
{
"plugins": ["babel-plugin-transform-regex"]
}Or to set plugin options:
{
"plugins": [["babel-plugin-transform-regex", {"removeImport": true}]]
}If you're using TypeScript, also add @babel/plugin-syntax-typescript.
Then add a script to your package.json to run the build:
"scripts": {
"build": "babel src --out-dir lib"
}After that, you can run it via npm run build.