or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-babel-preset-react-native

Babel preset for React Native applications with comprehensive JavaScript/TypeScript transformations and React Native runtime optimizations

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/babel-preset-react-native@4.0.x

To install, run

npx @tessl/cli install tessl/npm-babel-preset-react-native@4.0.0

index.mddocs/

babel-preset-react-native

A Babel preset specifically designed for React Native applications that provides comprehensive JavaScript and TypeScript transformations optimized for React Native's runtime environment. This preset includes a carefully curated set of Babel plugins for modern JavaScript features, React transformations, and mobile platform optimizations.

Package Information

  • Package Name: babel-preset-react-native (published as metro-react-native-babel-preset)
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install metro-react-native-babel-preset --save-dev

Core Imports

// As a Babel preset in .babelrc or babel.config.js
{
  "presets": ["module:metro-react-native-babel-preset"]
}

For programmatic usage:

const preset = require("metro-react-native-babel-preset");

// Use as Babel preset function
const config = preset(babelInstance, options);

// Direct access to preset generator
const { getPreset } = require("metro-react-native-babel-preset");
const presetConfig = getPreset(sourceCode, options);

Basic Usage

Most commonly used as a Babel preset in React Native projects:

{
  "presets": ["module:metro-react-native-babel-preset"]
}

With options:

{
  "presets": [
    [
      "module:metro-react-native-babel-preset",
      {
        "disableImportExportTransform": false,
        "dev": true
      }
    ]
  ]
}

Programmatic usage:

const preset = require("metro-react-native-babel-preset");
const babel = require("@babel/core");

// Transform code with the preset
const result = babel.transform(code, {
  presets: [[preset, { dev: true }]]
});

Capabilities

Default Preset Function

Main Babel preset factory function that creates transformation configuration.

/**
 * Creates a Babel preset configuration for React Native applications
 * @param {object} babel - Babel instance (standard Babel preset parameter, provides access to Babel's API)
 * @param {PresetOptions} options - Configuration options for the preset
 * @returns {PresetOutput} Babel preset configuration object with plugins and settings
 */
function preset(babel, options);

interface PresetOptions {
  /** Enable development-specific transformations (JSX source maps) */
  dev?: boolean;
  /** Override automatic environment detection for development tools
   * - null (default): Auto-detect from BABEL_ENV/NODE_ENV
   * - true: Force enable development features
   * - false: Force disable development features */
  withDevTools?: boolean | null;
  /** Skip ES6 import/export transformation to CommonJS */
  disableImportExportTransform?: boolean;
}

interface PresetOutput {
  /** Comments are stripped from transformed code */
  comments: false;
  /** Code is compacted for production */
  compact: true;
  /** Array of Babel plugins to apply */
  plugins: any[];
  /** TypeScript-specific plugin overrides */
  overrides: Array<{
    test: (filename: string) => boolean;
    plugins: any[];
  }>;
}

Source-Aware Preset Generator

Advanced preset configuration generator that optimizes plugin selection based on source code analysis.

/**
 * Generates preset configuration with conditional plugin loading based on source code analysis
 * @param {string | null} src - Source code string for analysis (null for all plugins)
 * @param {PresetOptions} options - Configuration options
 * @returns {PresetOutput} Optimized Babel preset configuration
 */
function getPreset(src, options);

Usage Example:

const { getPreset } = require("metro-react-native-babel-preset");

// Analyze source and get optimized config
const sourceCode = `
  class MyComponent extends React.Component {
    render() {
      return <div>Hello</div>;
    }
  }
`;

const config = getPreset(sourceCode, { dev: true });
// Will include class transformation plugins since 'class' is detected

Supported Transformations

The preset intelligently applies transformations based on source code analysis and environment settings:

Core JavaScript Features

  • Class Properties: @babel/plugin-proposal-class-properties (loose mode)
  • Object Rest/Spread: @babel/plugin-proposal-object-rest-spread
  • Arrow Functions: @babel/plugin-transform-arrow-functions
  • Block Scoping: @babel/plugin-transform-block-scoping
  • Classes: @babel/plugin-transform-classes
  • Computed Properties: @babel/plugin-transform-computed-properties
  • Destructuring: @babel/plugin-transform-destructuring
  • Function Names: @babel/plugin-transform-function-name
  • Literals: @babel/plugin-transform-literals
  • Parameters: @babel/plugin-transform-parameters
  • Shorthand Properties: @babel/plugin-transform-shorthand-properties
  • Spread Operator: @babel/plugin-transform-spread
  • Template Literals: @babel/plugin-transform-template-literals (loose mode - simple string concatenation instead of .concat())
  • For-of Loops: @babel/plugin-transform-for-of (loose mode for better performance)
  • Exponentiation Operator: @babel/plugin-transform-exponentiation-operator

Modern JavaScript Proposals

  • Optional Chaining: @babel/plugin-proposal-optional-chaining (loose mode for better performance)
  • Nullish Coalescing: @babel/plugin-proposal-nullish-coalescing-operator (loose mode for simpler output)
  • Optional Catch Binding: @babel/plugin-proposal-optional-catch-binding

React Transformations

  • JSX: @babel/plugin-transform-react-jsx
  • React Display Names: @babel/plugin-transform-react-display-name
  • JSX Source Maps: @babel/plugin-transform-react-jsx-source (development only)

Module System

  • CommonJS: @babel/plugin-transform-modules-commonjs with React Native optimizations:
    • strict: false - Prevents strict mode injection
    • strictMode: false - No "use strict" additions
    • allowTopLevelThis: true - Preserves global this references

Flow and TypeScript Support

  • Flow Type Stripping: @babel/plugin-transform-flow-strip-types
  • TypeScript: @babel/plugin-transform-typescript (for .ts/.tsx files)

Runtime Compatibility

  • Async/Await: @babel/plugin-transform-regenerator
  • Regex: @babel/plugin-transform-sticky-regex, @babel/plugin-transform-unicode-regex
  • Object.assign: @babel/plugin-transform-object-assign
  • Symbol Members: Custom transform that provides Symbol polyfill compatibility
// Input:
Symbol.iterator;

// Transformed output:
typeof Symbol === 'function' ? Symbol.iterator : '@@iterator';

Intelligent Plugin Loading

The preset uses source code analysis to conditionally load plugins for optimal performance:

// Only loads class transformation if 'class' keyword detected
const hasClass = src.indexOf('class') !== -1;

// Only loads arrow function transform if '=>' detected  
const hasArrowFunctions = src.indexOf('=>') !== -1;

// Only loads for-of transform if 'for' and 'of' detected together
const hasForOf = src.indexOf('for') !== -1 && src.indexOf('of') !== -1;

Environment Detection

Automatically detects development environment and enables appropriate features:

  • Development Mode: Enabled when BABEL_ENV=development, NODE_ENV=development, or options.dev=true
  • Development Features: JSX source maps for better debugging
  • Override: Use withDevTools option to explicitly control development features

TypeScript Support

Automatically detects and transforms TypeScript files with JSX support:

  • Detection: Files ending with .ts or .tsx (via isTypeScriptSource function)
  • Transform: Uses @babel/plugin-transform-typescript with isTSX: true to support JSX in TypeScript
  • Integration: TypeScript transform runs as an override after main plugin processing
  • Configuration: Always enables JSX support (isTSX: true) for React Native compatibility
  • Integration: Works seamlessly with all other preset transformations

Plugin Processing Order

Important: Plugin order is critical for correct transformation. The preset enforces specific ordering:

  1. Flow Type Stripping must come before Class Properties to avoid conflicts
  2. Default plugins are applied first (includes Flow, Class Properties, etc.)
  3. Conditional plugins are added based on source code analysis
  4. TypeScript override runs last for .ts/.tsx files

Configuration Examples

Basic React Native Setup

{
  "presets": ["module:metro-react-native-babel-preset"]
}

Development with Source Maps

{
  "presets": [
    ["module:metro-react-native-babel-preset", { "dev": true }]
  ]
}

Preserve ES6 Modules

{
  "presets": [
    [
      "module:metro-react-native-babel-preset", 
      { "disableImportExportTransform": true }
    ]
  ]
}

Force Development Mode

{
  "presets": [
    [
      "module:metro-react-native-babel-preset", 
      { "withDevTools": true }
    ]
  ]
}