babel-helper-module-imports
raw JSON → 7.0.0-beta.3 verified Sat Apr 25 auth: no javascript
Babel helper to insert module imports programmatically in AST transforms. v7.0.0-beta.3 is a prerelease of the 7.x series, part of the Babel ecosystem. This package provides functions like addDefault, addNamed, addSideEffect, and addNamespace to inject import statements during plugin execution. It abstracts away import creation, handling scoping, name collisions, and path insertion. The stable 7.x line is in maintenance; 8.x is in development with breaking changes. Key differentiator: designed for Babel plugin authors needing to add imports without manual AST construction.
Common errors
error TypeError: Cannot read properties of undefined (reading 'type') ↓
cause addDefault or addNamed called with invalid path (e.g., not a Program or statement path).
fix
Ensure the first argument is a valid Babel path (e.g., path from visitor).
Warnings
breaking API changes across major versions: Babel 8 may alter function signatures or import paths. ↓
fix Refer to Babel 8 migration guide; test plugins against target version.
deprecated The package name 'babel-helper-module-imports' is legacy; Babel 7+ uses scoped packages under @babel/. ↓
fix Prefer @babel/helper-module-imports in modern projects.
breaking Removal of default export in Babel 8: Some packages may drop default export support. ↓
fix Use named imports only.
Install
npm install babel-helper-module-imports yarn add babel-helper-module-imports pnpm add babel-helper-module-imports Imports
- addDefault wrong
const addDefault = require('babel-helper-module-imports').addDefaultcorrectimport { addDefault } from 'babel-helper-module-imports' - addNamed wrong
import addNamed from 'babel-helper-module-imports'correctimport { addNamed } from 'babel-helper-module-imports' - addSideEffect
import { addSideEffect } from 'babel-helper-module-imports' - addNamespace
import { addNamespace } from 'babel-helper-module-imports'
Quickstart
import { addDefault, addNamed } from 'babel-helper-module-imports';
import { types as t } from '@babel/core';
export default function() {
return {
visitor: {
Program(path) {
// Add default import: import lodash from 'lodash'
const defaultImport = addDefault(path, 'lodash');
// Add named import: import { map } from 'lodash'
const namedImport = addNamed(path, 'map', 'lodash', { nameHint: 'map' });
// Use the imported identifiers
console.log(defaultImport.name); // e.g., '_lodash'
console.log(namedImport.name); // e.g., '_map'
}
}
};
}