@babel/plugin-transform-logical-assignment-operators

logical-assignment-operators - 图1info

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

Example

In

JavaScript

  1. a ||= b;
  2. obj.a.b ||= c;
  3. a &&= b;
  4. obj.a.b &&= c;

Out

JavaScript

  1. var _obj$a, _obj$a2;
  2. a || (a = b);
  3. (_obj$a = obj.a).b || (_obj$a.b = c);
  4. a && (a = b);
  5. (_obj$a2 = obj.a).b && (_obj$a2.b = c);

With Nullish Coalescing

While using the @babel/plugin-transform-nullish-coalescing-operator plugin (included in @babel/preset-env)

JavaScript

  1. a ??= b;
  2. obj.a.b ??= c;

JavaScript

  1. var _a, _obj$a, _obj$a$b;
  2. (_a = a) !== null && _a !== void 0 ? _a : (a = b);
  3. (_obj$a$b = (_obj$a = obj.a).b) !== null && _obj$a$b !== void 0
  4. ? _obj$a$b
  5. : (_obj$a.b = c);

Installation

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-logical-assignment-operators
  1. yarn add --dev @babel/plugin-transform-logical-assignment-operators
  1. pnpm add --save-dev @babel/plugin-transform-logical-assignment-operators

Usage

babel.config.json

  1. {
  2. "plugins": ["@babel/plugin-transform-logical-assignment-operators"]
  3. }

Via CLI

Shell

  1. babel --plugins @babel/plugin-transform-logical-assignment-operators script.js

Via Node API

JavaScript

  1. require("@babel/core").transformSync("code", {
  2. plugins: ["@babel/plugin-transform-logical-assignment-operators"],
  3. });

References