babel-plugin-transform-regex

raw JSON →
6.1.0 verified Sat Apr 25 auth: no javascript

A Babel plugin that transpiles Regex+ template tag (`regex`…``) calls into native RegExp literals at build time. Current stable version is 6.1.0, updated January 2025. Releases are tied to the base Regex+ library. Key differentiators: eliminates runtime dependency, zero runtime cost, supports modern regex features (atomic groups, subroutines, definition groups, Unicode sets). Designed for Node.js and browser bundlers using Babel.

error Cannot find module 'regex'
cause Missing runtime dependency `regex` when the plugin is not used or some templates are not transformed.
fix
Install regex as a dependency: npm install regex
error Error: [BABEL] unknown plugin 'babel-plugin-transform-regex' specified in
cause Plugin is not installed as a devDependency.
fix
Run: npm install --save-dev babel-plugin-transform-regex
error Uncaught SyntaxError: Invalid regular expression: invalid flag v
cause Target environment does not support flag v (unicodeSets), but plugin outputs regexes with /v.
fix
Use Babel's @babel/plugin-transform-unicode-sets-regex or set disableUnicodeSets: true in plugin options.
breaking v4.3.0 changed the default flag for generated regexes from u to v (unicodeSets).
fix Ensure target environments support flag v or use option `disableUnicodeSets: true` to fall back to flag u.
deprecated Option `disableUnicodeSets` was added in v4.0.1 to replace the old behavior of always using flag u.
fix Use `disableUnicodeSets: true` if you need to avoid flag v in the output.
gotcha The plugin only transforms static `regex` tagged templates without dynamic interpolation. Variables or complex expressions inside the template are left untransformed.
fix Ensure all interpolated values are inline literals (strings, numbers, regexes) or `pattern` tags. Otherwise, the `regex` call remains at runtime.
gotcha The `optimize` option (experimental) uses regexp-tree optimizer which may produce incorrect results for flag-v-only syntax like nested character classes.
fix Test output thoroughly when using `optimize`. Consider not using it for complex patterns.
npm install babel-plugin-transform-regex
yarn add babel-plugin-transform-regex
pnpm add babel-plugin-transform-regex

Demonstrates setting up the Babel plugin and transforming a Regex+ template to a native RegExp literal with flag v.

// Install: npm install --save-dev babel-plugin-transform-regex regex
// .babelrc:
{
  "plugins": ["babel-plugin-transform-regex"]
}

// source.js:
import { regex } from 'regex';
const ipv4 = regex`
  ^ \g<byte> (\.\g<byte>){3} $
  (?(DEFINE)
    (?<byte> 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d)
  )
`;
// After Babel transform:
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;