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.
npm install babel-import-utilVerified import paths — ran on the pinned version, not inferred.
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.
Review the updated API documentation for v3.0.0 to adapt plugin logic, particularly around how identifiers are generated and managed by Babel's scope. Prioritize using higher-level methods like `replaceWith`.
Avoid using `babel-import-util@2.1.0`. Ensure you are on `^2.0.3` if targeting v2, or upgrade directly to `^3.0.0` for the latest stable API.
Ensure your plugin's `Program:enter` method includes `state.importUtil = new ImportUtil(babel, path);`.
Prefer `replaceWith`, `insertAfter`, or `insertBefore` whenever possible, as they handle binding updates and scope management automatically. Only use `import()` when you are explicitly managing Babel's scopes.
Initialize `state.importUtil = new ImportUtil(babel, path);` within the `Program:enter` visitor method of your plugin. Ensure `babel` and `path` are correctly passed.
Use `import { ImportUtil } from 'babel-import-util';` at the top of your plugin file. If in a CommonJS context (though this library is ESM-first), ensure proper interop or migrate to ESM.Change `import ImportUtil from 'babel-import-util';` to `import { ImportUtil } from 'babel-import-util';`.