@babel/plugin-proposal-private-property-in-object

NOTE: This plugin is included in @babel/preset-env, in ES2022

Example

In

  1. class Foo {
  2. #bar = "bar";
  3. test(obj) {
  4. return #bar in obj;
  5. }
  6. }

Out

  1. class Foo {
  2. constructor() {
  3. _bar.set(this, {
  4. writable: true,
  5. value: "bar",
  6. });
  7. }
  8. test() {
  9. return _bar.has(this);
  10. }
  11. }
  12. var _bar = new WeakMap();

Installation

  1. npm install --save-dev @babel/plugin-proposal-private-property-in-object

Usage

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

Via CLI

  1. babel --plugins @babel/plugin-proposal-private-property-in-object

Via Node API

  1. require("@babel/core").transformSync("code", {
  2. plugins: ["@babel/plugin-proposal-private-property-in-object"],
  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 property in expressions will check own properties (as opposed to inherited ones) on the object, instead of checking for presence inside 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.

⚠️ Consider migrating to the top level privateFieldsAsProperties assumption.

  1. // babel.config.json
  2. {
  3. "assumptions": {
  4. "privateFieldsAsProperties": true,
  5. "setPublicClassFields": true
  6. }
  7. }

Note that both privateFieldsAsProperties and setPublicClassFields must be set to true.

Example

In

  1. class Foo {
  2. #bar = "bar";
  3. test(obj) {
  4. return #bar in obj;
  5. }
  6. }

Out

  1. class Foo {
  2. constructor() {
  3. Object.defineProperty(this, _bar, {
  4. writable: true,
  5. value: "bar",
  6. });
  7. }
  8. test() {
  9. return Object.prototype.hasOwnProperty.call(this, _bar);
  10. }
  11. }
  12. var _bar = babelHelpers.classPrivateFieldLooseKey("bar");

You can read more about configuring plugin options here

References