@babel/plugin-transform-private-methods
这个插件包含在 @babel/preset-env 中,在 ES2022
历史
| 版本 | 变更 |
|---|---|
v7.3.0 | 支持私有访问器(getter 和 setter) |
v7.2.0 | 初始发布 |
示例
🌐 Example
class Counter extends HTMLElement {
#xValue = 0;
get #x() {
return this.#xValue;
}
set #x(value) {
this.#xValue = value;
window.requestAnimationFrame(this.#render.bind(this));
}
#clicked() {
this.#x++;
}
}
安装
🌐 Installation
- npm
- Yarn
- pnpm
- Bun
npm install @babel/plugin-transform-private-methods --save-dev
yarn add @babel/plugin-transform-private-methods --dev
pnpm add @babel/plugin-transform-private-methods --save-dev
bun add @babel/plugin-transform-private-methods --dev
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
没有选项:
🌐 Without options:
{
"plugins": ["@babel/plugin-transform-private-methods"]
}
有选项:
🌐 With options:
{
"plugins": [["@babel/plugin-transform-private-methods", { "loose": true }]]
}
通过 CLI
🌐 Via CLI
$ babel --plugins @babel/plugin-transform-private-methods script.js
通过 Node API
🌐 Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-private-methods"],
});
选项
🌐 Options
loose
boolean,默认值为 false。
loose 模式配置设置 必须 与 @babel/plugin-transform-class-properties 相同。
当为真时,私有方法将直接通过 Object.defineProperty 分配到其父级,而不是通过 WeakSet。这会提高性能和调试(普通属性访问 vs .get()),但代价是可能通过像 Object.getOwnPropertyNames 这样的方式泄露“私有”内容。
🌐 When true, private methods will be assigned directly on its parent
via Object.defineProperty rather than a WeakSet. This results in improved
performance and debugging (normal property access vs .get()) at the expense
of potentially leaking "privates" via things like Object.getOwnPropertyNames.
考虑迁移到顶层 privateFieldsAsProperties 假设。
{
"assumptions": {
"privateFieldsAsProperties": true,
"setPublicClassFields": true
}
}
注意,privateFieldsAsProperties 和 setPublicClassFields 都必须设置为 true。
🌐 Note that both privateFieldsAsProperties and setPublicClassFields must be set to true.
让我们使用以下示例:
🌐 Let's use the following as an example:
class Foo {
constructor() {
this.publicField = this.#privateMethod();
}
#privateMethod() {
return 42;
}
}
默认情况下,这变为:
🌐 By default, this becomes:
var Foo = function Foo() {
"use strict";
babelHelpers.classCallCheck(this, Foo);
_privateMethod.add(this);
this.publicField = babelHelpers
.classPrivateMethodGet(this, _privateMethod, _privateMethod2)
.call(this);
};
var _privateMethod = new WeakSet();
var _privateMethod2 = function _privateMethod2() {
return 42;
};
使用 { privateFieldsAsProperties: true },它变成了:
🌐 With { privateFieldsAsProperties: true }, it becomes:
var Foo = function Foo() {
"use strict";
babelHelpers.classCallCheck(this, Foo);
Object.defineProperty(this, _privateMethod, {
value: _privateMethod2,
});
this.publicField = babelHelpers
.classPrivateFieldLooseBase(this, _privateMethod)
[_privateMethod]();
};
var _privateMethod = babelHelpers.classPrivateFieldLooseKey("privateMethod");
var _privateMethod2 = function _privateMethod2() {
return 42;
};
你可以在这里了解更多关于配置插件选项的内容
参考
🌐 References