Skip to main content

@babel/plugin-transform-named-capturing-groups-regex

信息

此插件包含在 @babel/preset-env 中,在 ES2018 中注意:该插件生成需要 ES6 正则表达式功能的代码。如果你需要支持旧版浏览器,请使用 runtime: false 选项或导入适当的 polyfill(例如 core-js)。

¥This plugin is included in @babel/preset-env, in ES2018 NOTE: This plugin generates code that needs ES6 regular expressions functionalities. If you need to support older browsers, use either the runtime: false option or import a proper polyfill (e.g. core-js).

此插件转换正则表达式字面量以支持命名捕获组。它不会修补 new RegExp 构造函数,因为它的参数不能静态地预先转换:要处理函数/类的运行时行为,你需要改用 polyfill。

¥This plugin transforms regular expression literals to support named capturing groups. 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.

示例

¥Examples

输入

¥In

JavaScript
var re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;

console.log(re.exec("1999-02-29").groups.year);

输出

¥Out

JavaScript
var re = _wrapRegExp(/(\d{4})-(\d{2})-(\d{2})/, { year: 1, month: 2, day: 3 });

console.log(re.exec("1999-02-29").groups.year);

安装

¥Installation

npm install --save-dev @babel/plugin-transform-named-capturing-groups-regex

用法

¥Usage

¥With a configuration file (Recommended)

babel.config.json
{
"plugins": ["@babel/plugin-transform-named-capturing-groups-regex"]
}

通过 CLI

¥Via CLI

Shell
babel --plugins @babel/plugin-transform-named-capturing-groups-regex script.js

通过 Node API

¥Via Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-named-capturing-groups-regex"],
});

选项

¥Options

runtime

boolean,默认为 true

¥boolean, defaults to true

当这个选项被禁用时,Babel 不会用 _wrapRegExp 辅助程序封装 RegExps。输出仅支持内部组引用,不支持运行时属性:

¥When this option is disabled, Babel doesn't wrap RegExps with the _wrapRegExp helper. The output only supports internal group references, and not runtime properties:

JavaScript
var stringRe = /(?<quote>"|').*?\k<quote>/;

stringRe.test("'foo'"); // "true", works
stringRe.exec("'foo'").groups.quote; // Error
提示

你可以阅读有关配置插件选项 此处 的更多信息

¥You can read more about configuring plugin options here