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.

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.
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$').
npm install babel-plugin-auto-import
yarn add babel-plugin-auto-import
pnpm add babel-plugin-auto-import

Demonstrates basic auto-import for React and Component using .babelrc configuration.

// .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, []);