or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Babel Plugin Transform React JSX Self

Babel plugin that automatically adds a __self={this} prop to all JSX elements during compilation. This enables React DevTools and development-time debugging by providing better error reporting and component tracking capabilities.

Package Information

  • Package Name: @babel/plugin-transform-react-jsx-self
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev @babel/plugin-transform-react-jsx-self

Core Imports

To use the plugin programmatically:

import { declare } from "@babel/helper-plugin-utils";
import { types as t } from "@babel/core";
import pluginTransformReactJsxSelf from "@babel/plugin-transform-react-jsx-self";

For CommonJS:

const { declare } = require("@babel/helper-plugin-utils");
const { types: t } = require("@babel/core");
const pluginTransformReactJsxSelf = require("@babel/plugin-transform-react-jsx-self");

For Babel configuration usage:

// babel.config.js or .babelrc
{
  "plugins": ["@babel/plugin-transform-react-jsx-self"]
}

Basic Usage

The plugin works automatically when added to your Babel configuration. It transforms JSX elements by adding the __self prop:

// Input JSX
function Component() {
  return <div>Hello World</div>;
}

// Output after transformation
function Component() {
  return <div __self={this}>Hello World</div>;
}

Architecture

The plugin is built around several key components:

  • Plugin Factory: Uses Babel's declare() helper for version compatibility and API consistency
  • AST Visitor Pattern: Traverses the JavaScript AST to find and transform JSX elements
  • Context Analysis Engine: Sophisticated logic to determine when this references are safe to use
  • Safety Mechanisms: Prevents runtime errors by analyzing class hierarchies and function scoping
  • Transformation Logic: Adds JSX attributes while preserving existing props and element structure

Capabilities

JSX Self Transformation

Automatically adds __self={this} prop to all JSX elements for React development debugging.

/**
 * Main plugin factory function that creates a Babel plugin using declare helper
 * Uses Babel's declare() helper for version compatibility and API consistency
 */
export default declare((api: PluginAPI) => PluginObject);

/**
 * Plugin initialization requires Babel version 7 or higher
 */
api.assertVersion(REQUIRED_VERSION(7));

interface PluginObject {
  name: "transform-react-jsx-self";
  visitor: {
    Program(path: NodePath<Program>): void;
  };
}

/**
 * Constant defining the JSX attribute name added to elements
 */
const TRACE_ID = "__self";
/**
 * Internal visitor that handles the actual JSX transformation
 */
interface InternalVisitor {
  JSXOpeningElement(path: NodePath<JSXOpeningElement>): void;
}

The plugin intelligently handles edge cases:

  • Derived Class Constructors: Skips adding __self in derived class constructors before super() calls to prevent runtime errors
  • Arrow Functions: Properly handles this context in arrow functions vs regular functions
  • Method Context: Correctly identifies when this is available in different scoping contexts

Smart Context Detection

The plugin includes sophisticated internal logic to determine when it's safe to reference this. It analyzes the AST using several helper functions:

/**
 * Finds the closest parent function that provides `this` context
 * Excludes arrow functions as they don't rebind `this`
 */
function getThisFunctionParent(
  path: NodePath<JSXOpeningElement>
): NodePath<Exclude<FunctionParent, ArrowFunctionExpression>> | null;

/**
 * Returns whether the class has specified a superclass
 */
function isDerivedClass(classPath: NodePath<Class>): boolean;

/**
 * Returns whether `this` is allowed at given JSX element path
 * Performs comprehensive scope and context analysis
 */
function isThisAllowed(path: NodePath<JSXOpeningElement>): boolean;

This ensures that __self={this} is only added where it won't cause runtime errors.

Types

interface PluginAPI {
  version: string;
  assertVersion(range: number | string): void;
  types: typeof import("@babel/types");
}

interface PluginObject {
  name: string;
  visitor: {
    Program(path: NodePath<Program>): void;
  };
}

interface NodePath<T = Node> {
  node: T;
  scope: Scope;
  parentPath: NodePath | null;
  traverse(visitor: Visitor): void;
  isFunctionParent(): boolean;
  isArrowFunctionExpression(): boolean;
  isMethod(): boolean;
}

interface Visitor {
  JSXOpeningElement?(path: NodePath<JSXOpeningElement>): void;
  Program?(path: NodePath<Program>): void;
}

interface Scope {
  path: NodePath;
  parent: Scope | null;
}

type FunctionParent = Function | Method | ObjectMethod | ClassMethod | ArrowFunctionExpression;
type Class = ClassDeclaration | ClassExpression;

Configuration

This plugin accepts no configuration options. It works automatically when included in your Babel plugin list:

{
  "plugins": ["@babel/plugin-transform-react-jsx-self"]
}

The plugin requires Babel core version 7.0.0 or higher and is typically used only in development builds since the __self prop is primarily useful for debugging.

Error Handling

The plugin includes built-in safety mechanisms:

  • Runtime Error Prevention: Automatically skips __self injection in derived class constructors where this would cause errors
  • Version Compatibility: Asserts Babel version compatibility on initialization
  • Scope Analysis: Performs careful scope analysis to ensure this references are valid

Use Cases

  • React Development: Enhanced debugging experience with React DevTools
  • Error Reporting: Better stack traces and error messages in development
  • Component Tracking: Improved component identification in development tools
  • Development Builds: Typically used only in development configurations, not production