@babel/plugin-transform-nullish-coalescing-operator

nullish-coalescing-operator - 图1info

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

Example

In

JavaScript

  1. var foo = object.foo ?? "default";

Out

JavaScript

  1. var _object$foo;
  2. var foo =
  3. (_object$foo = object.foo) !== null && _object$foo !== void 0
  4. ? _object$foo
  5. : "default";

nullish-coalescing-operator - 图2note

We cannot use != null here because document.all == null and document.all has been deemed not “nullish”.

Installation

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-nullish-coalescing-operator
  1. yarn add --dev @babel/plugin-transform-nullish-coalescing-operator
  1. pnpm add --save-dev @babel/plugin-transform-nullish-coalescing-operator

Usage

babel.config.json

  1. {
  2. "plugins": ["@babel/plugin-transform-nullish-coalescing-operator"]
  3. }

Via CLI

Shell

  1. babel --plugins @babel/plugin-transform-nullish-coalescing-operator script.js

Via Node API

JavaScript

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

Options

loose

boolean, defaults to false.

When true, this transform will pretend document.all does not exist, and perform loose equality checks with null instead of strict equality checks against both null and undefined.

nullish-coalescing-operator - 图3caution

Consider migrating to the top level noDocumentAll assumption.

babel.config.json

  1. {
  2. "assumptions": {
  3. "noDocumentAll": true
  4. }
  5. }

Example

In

JavaScript

  1. var foo = object.foo ?? "default";

Out

JavaScript

  1. var _object$foo;
  2. var foo = (_object$foo = object.foo) != null ? _object$foo : "default";

nullish-coalescing-operator - 图4tip

You can read more about configuring plugin options here

References