This Babel plugin transforms Unicode property escapes in regular expressions to make them compatible with ES5 environments. It converts modern Unicode regex features (like \p{Script=Greek} or \p{Alphabetic}) into equivalent patterns that work in older JavaScript engines.
npm install --save-dev @babel/plugin-transform-unicode-property-regex// CommonJS
const plugin = require("@babel/plugin-transform-unicode-property-regex");
// ES Modules
import plugin from "@babel/plugin-transform-unicode-property-regex";
// Named import of Options type (TypeScript)
import plugin, { type Options } from "@babel/plugin-transform-unicode-property-regex";Add the plugin to your Babel configuration:
// babel.config.js
module.exports = {
plugins: [
"@babel/plugin-transform-unicode-property-regex"
]
};With options:
// babel.config.js
module.exports = {
plugins: [
["@babel/plugin-transform-unicode-property-regex", {
useUnicodeFlag: false
}]
]
};Input code:
const hexPattern = /\p{ASCII_Hex_Digit}/u;
const letterPattern = /\p{Letter}/u;With useUnicodeFlag: true (default):
const hexPattern = /[0-9A-Fa-f]/u;
const letterPattern = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]/u;With useUnicodeFlag: false:
const hexPattern = /[0-9A-Fa-f]/;
const letterPattern = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]/;The main export is a Babel plugin factory function that creates the transform plugin.
/**
* Creates a Babel plugin that transforms Unicode property escapes in regular expressions
* @param api - Babel API object with version assertion
* @param options - Plugin configuration options
* @returns Babel plugin object
*/
declare function default(api: BabelApi, options?: Options): BabelPlugin;
interface BabelApi {
assertVersion(version: number | string): void;
}Configuration options for customizing the plugin behavior.
interface Options {
/**
* Whether to preserve the unicode flag in transformed regular expressions
* @default true
*/
useUnicodeFlag?: boolean;
}The plugin validates its options and throws errors for invalid configurations:
useUnicodeFlag is not a boolean or undefined
@babel/helper-create-regexp-features-pluginThe plugin leverages Babel's helper infrastructure to detect and transform Unicode property escapes while maintaining the original regex functionality. It's designed for use in build pipelines where modern JavaScript code needs to run in environments that don't support Unicode property escapes natively.