@babel/plugin-transform-unicode-sets-regex
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
信息
本插件已包含在 @babel/preset-env 的 ES2024 配置中
本插件将通过 RegExp 集合符号 + 字符串属性提案引入的 v 标志符的正则表达式,转换为使用 u 标志符的正则表达式。
它仅转换 /.../v 语法,不修改 new RegExp 构造函数的行为——因为其参数无法静态预转换:如需处理函数/类的运行时行为,您需要使用 polyfill 替代方案。
示例
交集
input.js
/[\p{ASCII}&&\p{Decimal_Number}]/v;
将被转换为
output.js
/[0-9]/u;
差集
input.js
// Non-ASCII white spaces
/[\p{White_Space}--\p{ASCII}]/v;
将被转换为
output.js
/[\x85\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/u;
字符串属性
input.js
/^\p{Emoji_Keycap_Sequence}$/v.test("*\uFE0F\u20E3");
// true
将被转换为
output.js
/^(?:\*️⃣|#️⃣|0️⃣|1️⃣|2️⃣|3️⃣|4️⃣|5️⃣|6️⃣|7️⃣|8️⃣|9️⃣)$/u.test("*\uFE0F\u20E3");
// true
这是支持属性列表。注意:在 u 标志符中使用字符串属性会导致错误。
input.js
/\p{Emoji_Keycap_Sequence}/u;
// Error: Properties of strings are only supported when using the unicodeSets (v) flag.
安装
- 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
用法
通过配置文件(推荐)
babel.config.json
{
"plugins": ["@babel/plugin-transform-unicode-sets-regex"]
}
通过命令行
Shell
babel --plugins @babel/plugin-transform-unicode-sets-regex script.js
通过 Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-unicode-sets-regex"],
});