Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

babel-plugin-defer

gchumillas0MIT1.0.4TypeScript support: included

Babel plugin that transpiles defer statements to JavaScript, bringing Go-like defer functionality to JavaScript/TypeScript applications

babel, babel-plugin, defer, transpiler, javascript, typescript, go, cleanup, resource-management

readme

babel-plugin-defer

npm version License: MIT TypeScript

A Babel plugin that transpiles defer statements to JavaScript, bringing Go-like defer functionality to JavaScript/TypeScript applications.

Overview

babel-plugin-defer is a Babel transpiler plugin that enables developers to use defer statements in JavaScript and TypeScript, similar to the defer mechanism found in languages like Go and V. The plugin automatically transpiles defer calls into proper JavaScript code that executes cleanup functions at the end of the current scope.

import { defer } from 'babel-plugin-defer/runtime'

function processFile(filename) {
    const file = fs.openSync(filename)
    defer(() => fs.closeSync(file)) // Transpiled to proper cleanup

    // Process file...
    // file.close() will be called automatically
}

What is defer?

The defer statement is a powerful control flow mechanism that schedules a function call to be executed when the surrounding function returns. This pattern is commonly used for:

  • Resource cleanup: Closing files, database connections, or network sockets
  • Lock management: Releasing mutexes or semaphores
  • Logging: Recording function exit points
  • Error handling: Ensuring cleanup code runs even when errors occur

defer in other languages

Go:

func processFile(filename string) error {
    file, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer file.Close() // Will be called when function returns

    // Process file...
    return nil
}

V:

fn process_file(filename string) ! {
    mut file := os.open(filename)!
    defer { file.close() } // Cleanup guaranteed

    // Process file...
}

Installation

Install the package and the peer dependency:

npm install babel-plugin-defer
npm install --save-dev @babel/core

Visit the examples folder for more examples.

Usage

Import the functions you need from the runtime package:

import { defer } from 'babel-plugin-defer/runtime'

function example() {
  const resource = acquireResource()
  defer(() => resource.cleanup()) // Will be transpiled to try/finally

  // Your code here...
  // cleanup() will be called automatically when function exits
}

[!NOTE] When using the Babel plugin, these function calls are transpiled at build time into optimized JavaScript code. The runtime functions serve as fallbacks for environments where Babel is not configured.

How it works

The plugin transforms defer statements during the build process:

Input:

function processData() {
  const conn = database.connect()
  defer(() => conn.close()) // or simply defer(conn.close)

  const file = filesystem.open('path/to/file.txt')
  defer(() => file.close()) // or simply defer(file.close)

  const data = conn.query('SELECT * FROM users')
  return data
}

Output (transpiled):

function processData() {
  const _defers = [];
  try {
    const conn = database.connect();
    _defers.push(() => conn.close());

    const file = filesystem.open('path/to/file.txt');
    _defers.push(() => file.close());

    const data = conn.query('SELECT * FROM users');
    return data;
  } finally {
    // Closes the resources in reverse order
    for (let i = _defers.length - 1; i >= 0; i--) {
      try {
        _defers[i]();
      } catch (e) {
        console.log(e);
      }
    }
  }
}

API Reference

defer(fn: () => void): void

Schedules a function to be executed when the current function scope exits.

Parameters:

  • fn: A function to be called during cleanup

Example:

function handleRequest() {
  const startTime = Date.now()
  defer(() => console.log(`Request took ${Date.now() - startTime}ms`))

  // Handle request...
}

TypeScript Support

The plugin includes full TypeScript support with global type declarations. The defer function is automatically available in your TypeScript files without additional imports.

Development

# Clone the repository
git clone https://github.com/your-username/babel-plugin-defer.git
cd babel-plugin-defer

# Install dependencies
npm install

# Build the plugin
npm run build

# Run tests
npm test

# Run with watch mode
npm run test:watch

# Lint code
npm run lint

# Prepare for publishing
npm run prepublishOnly

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

License

MIT © Your Name

Changelog

See CHANGELOG.md for a detailed history of changes.

Support

If this package is helpful to you, please consider:

  • ⭐ Starring the repository
  • 🐛 Reporting issues
  • 💡 Suggesting new features
  • 🔗 Sharing with others

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[1.0.0] - 2025-06-26

Added

  • Initial release of babel-plugin-defer
  • Support for defer statement transpilation to try/finally blocks
  • Runtime fallback functions for environments without Babel
  • Full TypeScript support with type declarations
  • Vite integration support
  • Comprehensive documentation and examples

Features

  • Transpiles defer(() => cleanup()) to proper try/finally blocks
  • Browser-safe runtime exports at /runtime
  • Zero dependencies in runtime bundle
  • Full compatibility with React, Vite, and modern build tools