or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-babel--plugin-transform-nullish-coalescing-operator

Transforms the nullish coalescing operator (??) into conditional expressions compatible with older JavaScript environments.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@babel/plugin-transform-nullish-coalescing-operator@7.27.x

To install, run

npx @tessl/cli install tessl/npm-babel--plugin-transform-nullish-coalescing-operator@7.27.0

index.mddocs/

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

@babel/plugin-transform-nullish-coalescing-operator is a Babel plugin that transforms the nullish coalescing operator (??) into conditional expressions compatible with older JavaScript environments. It provides comprehensive transformation handling edge cases like document.all behavior, supports loose mode for simpler transformations, and includes optimizations for pure getters and identifiers.

Package Information

  • Package Name: @babel/plugin-transform-nullish-coalescing-operator
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev @babel/plugin-transform-nullish-coalescing-operator

Core Imports

// ESM
import nullishCoalescingPlugin from "@babel/plugin-transform-nullish-coalescing-operator";

// ESM with Options interface
import nullishCoalescingPlugin, { Options } from "@babel/plugin-transform-nullish-coalescing-operator";

// TypeScript with type imports
import nullishCoalescingPlugin, { type Options } from "@babel/plugin-transform-nullish-coalescing-operator";

// CommonJS
const nullishCoalescingPlugin = require("@babel/plugin-transform-nullish-coalescing-operator");
const { Options } = require("@babel/plugin-transform-nullish-coalescing-operator");

Basic Usage

With Babel Config

// babel.config.js
module.exports = {
  plugins: [
    "@babel/plugin-transform-nullish-coalescing-operator"
  ]
};

With Options

// babel.config.js
module.exports = {
  plugins: [
    ["@babel/plugin-transform-nullish-coalescing-operator", {
      loose: true
    }]
  ]
};

Transformation Example

Input JavaScript with nullish coalescing:

function getUserName(user) {
  return user.name ?? "Anonymous";
}

const config = {
  timeout: options.timeout ?? 5000,
  retries: options.retries ?? 3
};

Output after transformation:

function getUserName(user) {
  var _user$name;
  return (_user$name = user.name) !== null && _user$name !== undefined ? _user$name : "Anonymous";
}

const config = {
  timeout: options.timeout != null ? options.timeout : 5000,
  retries: options.retries != null ? options.retries : 3
};

Capabilities

Main Plugin Export

The package exports a Babel plugin created using the declare helper from @babel/helper-plugin-utils. The plugin transforms nullish coalescing operators into conditional expressions.

/**
 * Main plugin export created using Babel's declare helper
 * The plugin transforms nullish coalescing operators into conditional expressions
 */
declare const plugin: BabelPlugin;

export default plugin;
export { Options };

Plugin Configuration Options

Configuration options for customizing the transformation behavior.

interface Options {
  /**
   * Enable loose mode transformation
   * When true, uses `!= null` instead of explicit null and undefined checks
   * @default false
   */
  loose?: boolean;
}

Babel Plugin Object

The plugin returns a standard Babel plugin object with visitor methods.

interface BabelPlugin {
  /** Plugin name identifier */
  name: "transform-nullish-coalescing-operator";
  
  /** Parser plugin configuration (Babel 7 only) */
  manipulateOptions?: (opts: any, parser: any) => void;
  
  /** AST visitor methods */
  visitor: {
    LogicalExpression: (path: NodePath<LogicalExpression>) => void;
  };
}

Transformation Behavior

Standard Mode (loose: false)

In standard mode, the plugin performs spec-compliant transformations that handle the document.all edge case:

  • a ?? b becomes a !== null && a !== undefined ? a : b
  • Uses explicit null and undefined checks to maintain spec compliance
  • Creates temporary variables to avoid duplicate evaluation

Loose Mode (loose: true)

In loose mode, the plugin uses simpler transformations for better performance:

  • a ?? b becomes a != null ? a : b
  • Uses loose equality check (!= null) which covers both null and undefined
  • Still avoids duplicate evaluation with temporary variables when needed

Optimization Features

The plugin includes several optimizations based on Babel assumptions:

Pure Getters Assumption

When pureGetters assumption is enabled:

  • Avoids creating temporary variables for simple member expressions (obj.prop)
  • Assumes getter functions have no side effects
  • Reduces generated code size for common patterns

No Document.All Assumption

When noDocumentAll assumption is enabled:

  • Uses loose mode transformation even when loose: false
  • Assumes document.all behavior is not a concern in the target environment
  • Generates simpler and more performant code

Supported Contexts

The plugin handles nullish coalescing in various JavaScript contexts:

Basic Expressions

// Input
const value = a ?? b;

// Output (standard mode)
const value = a !== null && a !== undefined ? a : b;

Function Parameters

// Input
function example(param = a ?? b) { }

// Output
function example(param = (() => a ?? b)()) { }

Destructuring Defaults

// Input
const { prop = a ?? b } = obj;

// Output (transformed to avoid scope issues)
const { prop = (() => a ?? b)() } = obj;

Nested Expressions

// Input
const result = (obj.prop ?? defaultObj).method();

// Output
var _obj$prop;
const result = ((_obj$prop = obj.prop) !== null && _obj$prop !== undefined ? _obj$prop : defaultObj).method();

Integration with Babel Ecosystem

Required Dependencies

  • @babel/core: ^7.0.0-0 (peer dependency)
  • @babel/helper-plugin-utils: For plugin declaration utilities

Babel Version Compatibility

  • Supports Babel 7.x and later
  • Automatically registers the nullishCoalescingOperator parser plugin in Babel 7
  • Compatible with Babel 8 breaking changes

Parser Plugin Integration

The plugin automatically configures the Babel parser to recognize nullish coalescing syntax:

// Automatically added parser plugin
parser.plugins.push("nullishCoalescingOperator");

Assumptions Support

The plugin respects Babel's assumption system for optimization:

// babel.config.js with assumptions
module.exports = {
  assumptions: {
    "pureGetters": true,
    "noDocumentAll": true
  },
  plugins: [
    "@babel/plugin-transform-nullish-coalescing-operator"
  ]
};

Types

interface BabelAPI {
  assertVersion: (version: number) => void;
  assumption: (name: string) => boolean | undefined;
}

interface NodePath<T> {
  node: T;
  scope: Scope;
  replaceWith: (node: any) => void;
}

interface LogicalExpression {
  operator: string;
  left: Expression;
  right: Expression;
}

interface Scope {
  generateUidIdentifierBasedOnNode: (node: any) => Identifier;
  push: (binding: { id: Identifier }) => void;
  hasBinding: (name: string) => boolean;
  buildUndefinedNode: () => Identifier;
  path: NodePath<any>;
}

interface Expression {
  // Base AST node type for expressions
}

interface Identifier extends Expression {
  name: string;
}