Babel Import Utility

3.0.1 · active · verified Sun Apr 19

babel-import-util is a utility library designed to simplify the process of manipulating imports within Babel plugins. It provides an API for safely emitting new imported names, ensuring correct composition with other Babel plugins by updating Babel's binding understanding, and automatically deduplicating redundant imports. The library is written in TypeScript and ships with type definitions, making it well-suited for TypeScript-based plugin development. The current stable version is 3.0.1, released in March 2025, indicating active maintenance and a regular release cadence. Key differentiators include its focus on reference-aware APIs (introduced in v3.0.0) that improve safety and correctness when working with Babel's AST, and its ability to handle import deduplication and binding updates transparently, reducing boilerplate for plugin authors.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `babel-import-util` within a Babel plugin to replace a `myTarget()` call with `theMethod()` imported from 'my-implementation', ensuring correct binding and deduplication. It highlights the required instantiation of `ImportUtil` at the `Program` scope.

import type { NodePath } from '@babel/traverse';
import type * as t from '@babel/types';
import { ImportUtil } from 'babel-import-util';

function testTransform(babel: { types: typeof t }) {
  return {
    visitor: {
      Program: {
        enter(path: NodePath<t.Program>, state: { importUtil?: ImportUtil }) {
          // Always instantiate the ImportUtil instance at the Program scope
          state.importUtil = new ImportUtil(babel, path);
        }
      },
      CallExpression(path: NodePath<t.CallExpression>, state: { importUtil?: ImportUtil }) {
        const callee = path.get('callee');
        if (callee.isIdentifier() && callee.node.name === 'myTarget') {
          if (!state.importUtil) {
            throw new Error('ImportUtil not initialized. Ensure it is instantiated in Program:enter.');
          }
          state.importUtil.replaceWith(callee, (i) =>
            i.import(callee, 'my-implementation', 'theMethod')
          );
        }
      }
    }
  };
}

view raw JSON →