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

private-property-in-object - 图1info

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

Example

In

JavaScript

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

Out

JavaScript

  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

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-private-property-in-object
  1. yarn add --dev @babel/plugin-transform-private-property-in-object
  1. pnpm add --save-dev @babel/plugin-transform-private-property-in-object

Usage

babel.config.json

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

Via CLI

Shell

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

Via Node API

JavaScript

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

Options

loose

boolean, defaults to false.

private-property-in-object - 图2note

The loose mode configuration setting must be the same as @babel/transform-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.

private-property-in-object - 图3caution

Consider migrating to the top level privateFieldsAsProperties assumption.

babel.config.json

  1. {
  2. "assumptions": {
  3. "privateFieldsAsProperties": true,
  4. "setPublicClassFields": true
  5. }
  6. }

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

Example

In

JavaScript

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

Out

JavaScript

  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");

private-property-in-object - 图4tip

You can read more about configuring plugin options here

References