babel-plugin-auto-import
raw JSON → 1.1.0 verified Sat Apr 25 auth: no javascript
A Babel plugin that automatically converts global variable references into import statements at build time. The current stable version is 1.1.0. It has a low release cadence with no recent updates. It differs from similar plugins (like babel-plugin-import) by supporting anonymous imports for side-effect modules, dynamic path generation based on filename, and flexible declaration syntax for default, named, and mixed imports. It is widely used in Create React App setups via react-app-rewired.
Common errors
error Unknown plugin "auto-import" specified in "plugins" ↓
cause Plugin is not installed or name is mistyped in config.
fix
Run
npm install --save-dev babel-plugin-auto-import and check spelling. error Error: .plugins[0][0] must be a string, function, or object ↓
cause Plugin options are not wrapped in a tuple array.
fix
Change to [["auto-import", { ... }]].
error ReferenceError: React is not defined ↓
cause Auto-import declaration missing or incorrect path.
fix
Add {"default": "React", "path": "react"} to declarations.
Warnings
gotcha Plugin options must be wrapped in an array tuple in .babelrc/programmatic config; omitting the outer array causes 'Invalid Plugin' error. ↓
fix Use [["auto-import", { ... }]] instead of ["auto-import", { ... }].
gotcha Anonymous imports for side-effect modules require the 'anonymous' array, not 'default' or 'members'. ↓
fix Use {"anonymous": ["fetch"], "path": "whatwg-fetch"}.
gotcha Filename-based path generation with [name] uses the current file's basename. Mismatched patterns cause unresolved imports. ↓
fix Verify nameReplacePattern matches file extension exactly (e.g., '\\.js$').
Install
npm install babel-plugin-auto-import yarn add babel-plugin-auto-import pnpm add babel-plugin-auto-import Imports
- auto-import (babel plugin) wrong
{"plugins": ["auto-import", {...}]}correct// In .babelrc: {"plugins": [["auto-import", {...}]]} - React auto-import wrong
{"declarations": [{"default": "React", "path": "react", "members": ["Component"]}]}correct{"declarations": [{"default": "React", "members": ["Component"], "path": "react"}]} - Side-effect import wrong
{"declarations": [{"default": "fetch", "path": "whatwg-fetch"}]}correct{"declarations": [{"anonymous": ["fetch"], "path": "whatwg-fetch"}]}
Quickstart
// .babelrc
{
"plugins": [[
"auto-import", {
"declarations": [
{ "default": "React", "path": "react" },
{ "default": "Component", "path": "react" }
]
}
]]
}
// input.js
React.createElement('div', null, []);
// output.js
import React from "react";
React.createElement('div', null, []);