@babel/plugin-transform-unicode-sets-regex
这个插件包含在 @babel/preset-env 中,在 ES2024
这个插件将使用 [RegExp 集合表示法 + 字符串属性](https://github.com/tc39/proposal-regexp-set-notation) 提案中引入的 v 标志的正则表达式,转换为使用 u 标志的正则表达式。
🌐 This plugin transforms regular expressions using the v flag, introduced by the RegExp set notation + properties of strings proposal, to regular expressions that use the u flag.
它只会转换 /.../v 语法,并不会修补 new RegExp 构造函数,因为它的参数无法被静态预转换:要处理函数/类的运行时行为,你需要使用 polyfill。
🌐 It only transforms /.../v syntax and it does not patch the new RegExp constructor, since its arguments cannot be pre-transformed statically: to handle runtime behavior of functions/classes, you will need to use a polyfill instead.
示例
🌐 Example
交集
🌐 Intersection
/[\p{ASCII}&&\p{Decimal_Number}]/v;
将转变为
🌐 will be transformed to
/[0-9]/u;
不同之处
🌐 Difference
// Non-ASCII white spaces
/[\p{White_Space}--\p{ASCII}]/v;
将转变为
🌐 will be transformed to
/[\x85\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/u;
字符串的属性
🌐 Property of Strings
/^\p{Emoji_Keycap_Sequence}$/v.test("*\uFE0F\u20E3");
// true
将转变为
🌐 will be transformed to
/^(?:\*️⃣|#️⃣|0️⃣|1️⃣|2️⃣|3️⃣|4️⃣|5️⃣|6️⃣|7️⃣|8️⃣|9️⃣)$/u.test("*\uFE0F\u20E3");
// true
这里有一个支持的属性列表。注意,使用带有 u 标志的字符串属性会报错。
🌐 Here is a list of supported properties. Note that using property of strings with u-flag will error.
/\p{Emoji_Keycap_Sequence}/u;
// Error: Properties of strings are only supported when using the unicodeSets (v) flag.
安装
🌐 Installation
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-unicode-sets-regex
yarn add --dev @babel/plugin-transform-unicode-sets-regex
pnpm add --save-dev @babel/plugin-transform-unicode-sets-regex
bun add --dev @babel/plugin-transform-unicode-sets-regex
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
{
"plugins": ["@babel/plugin-transform-unicode-sets-regex"]
}
通过 CLI
🌐 Via CLI
babel --plugins @babel/plugin-transform-unicode-sets-regex script.js
通过 Node API
🌐 Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-unicode-sets-regex"],
});