@babel/plugin-proposal-private-methods

Example

  1. class Counter extends HTMLElement {
  2. #xValue = 0;
  3. get #x() { return this.#xValue; }
  4. set #x(value) {
  5. this.#xValue = value;
  6. window.requestAnimationFrame(
  7. this.#render.bind(this));
  8. }
  9. #clicked() {
  10. this.#x++;
  11. }
  12. }

Installation

  1. $ npm install @babel/plugin-proposal-private-methods

Usage

Without options:

  1. {
  2. "plugins": ["@babel/plugin-proposal-private-methods"]
  3. }

With options:

  1. {
  2. "plugins": [["@babel/plugin-proposal-private-methods", { "loose": true }]]
  3. }

Via CLI

  1. $ babel --plugins @babel/plugin-proposal-private-methods script.js

Via Node API

  1. require("@babel/core").transform("code", {
  2. plugins: ["@babel/plugin-proposal-private-methods"],
  3. });

Options

loose

boolean, defaults to false.

Note: The loose mode configuration setting must be the same as @babel/proposal-class-properties.

When true, private methods will be assigned directly on its parentvia Object.defineProperty rather than a WeakSet. This results in improvedperformance and debugging (normal property access vs .get()) at the expenseof potentially leaking "privates" via things like Object.getOwnPropertyNames.

Let's use the following as an example:

  1. class Foo {
  2. constructor() {
  3. this.publicField = this.#privateMethod();
  4. }
  5. #privateMethod() {
  6. return 42;
  7. }
  8. }

By default, this becomes:

  1. var Foo = function Foo() {
  2. "use strict";
  3. babelHelpers.classCallCheck(this, Foo);
  4. _privateMethod.add(this);
  5. this.publicField = babelHelpers
  6. .classPrivateMethodGet(this, _privateMethod, _privateMethod2)
  7. .call(this);
  8. };
  9. var _privateMethod = new WeakSet();
  10. var _privateMethod2 = function _privateMethod2() {
  11. return 42;
  12. };

With { loose: true }, it becomes:

  1. var Foo = function Foo() {
  2. "use strict";
  3. babelHelpers.classCallCheck(this, Foo);
  4. Object.defineProperty(this, _privateMethod, {
  5. value: _privateMethod2,
  6. });
  7. this.publicField = babelHelpers
  8. .classPrivateFieldLooseBase(this, _privateMethod)
  9. [_privateMethod]();
  10. };
  11. var _privateMethod = babelHelpers.classPrivateFieldLooseKey("privateMethod");
  12. var _privateMethod2 = function _privateMethod2() {
  13. return 42;
  14. };

You can read more about configuring plugin options here

References