or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-babel-plugin-transform-do-expressions

Babel plugin that transforms ECMAScript do expressions into ES5-compatible code

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/babel-plugin-transform-do-expressions@6.22.x

To install, run

npx @tessl/cli install tessl/npm-babel-plugin-transform-do-expressions@6.22.0

index.mddocs/

babel-plugin-transform-do-expressions

Babel plugin that transforms ECMAScript do expressions into standard JavaScript code. Do expressions allow developers to use block statements as expressions, where the completion value of the final statement becomes the value of the entire do expression. The plugin works by extracting the contents of do expressions and relying on JavaScript's native statement completion semantics.

Package Information

  • Package Name: babel-plugin-transform-do-expressions
  • Package Type: npm
  • Language: JavaScript (ES5/ES6)
  • Installation: npm install --save-dev babel-plugin-transform-do-expressions

Core Imports

The plugin is used through Babel configuration, not direct imports:

.babelrc configuration:

{
  "plugins": ["transform-do-expressions"]
}

CLI usage:

babel --plugins transform-do-expressions script.js

Node API usage:

require("babel-core").transform("code", {
  plugins: ["transform-do-expressions"]
});

Basic Usage

Do expressions allow complex conditional logic to be embedded as expressions:

// Input: Do expression syntax
let result = do {
  if (x > 10) {
    'big';
  } else {
    'small';
  }
};

// Output: Transformed to use statement completion values
// The plugin transforms the DoExpression by extracting its body statements
// and relying on JavaScript's statement completion value semantics
let result = (() => {
  if (x > 10) {
    'big';
  } else {
    'small';
  }
})();

JSX Usage Example:

// Input: Complex conditional logic in JSX
const Component = props =>
  <div className='myComponent'>
    {do {
      if(color === 'blue') { <BlueComponent/>; }
      if(color === 'red') { <RedComponent/>; }
      if(color === 'green') { <GreenComponent/>; }
    }}
  </div>;

// Output: Transformed JSX
// The plugin extracts the do expression body statements
const Component = props =>
  <div className='myComponent'>
    {(() => {
      if(color === 'blue') { <BlueComponent/>; }
      if(color === 'red') { <RedComponent/>; }
      if(color === 'green') { <GreenComponent/>; }
    })()}
  </div>;

Architecture

The plugin uses Babel's AST visitor pattern to transform DoExpression nodes:

  • Inheritance: Inherits from babel-plugin-syntax-do-expressions for parsing support
  • Transformation Phase: Operates during Babel's transformation phase after syntax parsing
  • AST Processing: Visits DoExpression nodes and replaces them directly with their body statements
  • Completion Values: Relies on JavaScript's native statement completion value semantics
  • Simple Transform: No wrapper functions are generated - the plugin simply extracts the block contents

Capabilities

Plugin Factory Function

Main export that returns the Babel plugin configuration.

/**
 * Default export: Babel plugin factory function
 * @returns {Object} Babel plugin configuration object
 */
export default function(): {
  inherits: any;
  visitor: {
    DoExpression: (path: any) => void;
  };
};

Do Expression Transformation

The plugin transforms do expressions through a simple process of extracting block contents:

  1. Empty do expressions: do {}undefined (using buildUndefinedNode())
  2. Non-empty expressions: The DoExpression node is replaced with its body statements using replaceWithMultiple()
  3. Statement completion values: JavaScript's native completion value semantics handle the final expression value
  4. No wrapper generation: The plugin does not generate IIFEs or wrapper functions

Transformation Logic:

/**
 * AST visitor method for DoExpression nodes
 * @param {Object} path - Babel AST path object containing the DoExpression node
 */
DoExpression(path) {
  const body = path.node.body.body;
  if (body.length) {
    // Replace the do expression with its body statements
    path.replaceWithMultiple(body);
  } else {
    // Empty do expressions become undefined
    path.replaceWith(path.scope.buildUndefinedNode());
  }
}

Note: This transformation relies on JavaScript's statement completion values - the final statement in a block becomes the completion value of that block.

### Plugin Configuration

The plugin returns a standard Babel plugin configuration object:

The plugin configuration object structure:

```javascript { .api }
{
  // Inherits syntax parsing capabilities
  inherits: require("babel-plugin-syntax-do-expressions"),
  // AST visitor methods
  visitor: {
    // Visitor method for DoExpression nodes
    DoExpression: function(path) {
      // Transform logic here
    }
  }
}

Dependencies

  • babel-plugin-syntax-do-expressions: ^6.8.0 - Provides parsing support for do expression syntax
  • babel-runtime: ^6.22.0 - Babel runtime helpers for plugin execution

Examples

Test Case Examples

Based on the plugin's test suite, here are the actual transformations:

// Empty do expression
do {} // → undefined

// Single expression
do { "foo"; } // → "foo"

// Conditional expression  
do {
  if (true) {
    "bar";
  }
} // → "bar" (when condition is true)

Simple Conditional

// Input
let status = do {
  if (user.isAdmin) {
    'admin';
  } else if (user.isModerator) {
    'moderator';
  } else {
    'user';
  }
};

// Output: Statement completion values preserved
let status = (() => {
  if (user.isAdmin) {
    'admin';
  } else if (user.isModerator) {
    'moderator';
  } else {
    'user';
  }
})();

Complex Logic

// Input
let result = do {
  let temp = expensive_calculation();
  if (temp > threshold) {
    temp * factor;
  } else {
    fallback_value;
  }
};

// Output: Block contents extracted, completion value preserved
let result = (function() {
  let temp = expensive_calculation();
  if (temp > threshold) {
    temp * factor;
  } else {
    fallback_value;
  }
})();

Empty Expression

// Input
let value = do {};

// Output
let value = undefined;

Error Handling

The plugin handles transformation edge cases:

  • Empty blocks: Replaced with undefined
  • Nested do expressions: Each transformed independently
  • Complex control flow: Preserves original semantics
  • Variable declarations: Maintains proper scoping

The plugin integrates with Babel's error reporting system for syntax and transformation errors.