Bun Auto-Imports Plugin

0.4.0 · active · verified Tue Apr 21

bun-plugin-auto-imports is a utility plugin designed for the Bun bundler, enabling automatic import resolution and injection into JavaScript and TypeScript files during the build process. It streamlines development by reducing the need for explicit import statements, similar to features found in other build tools like Vite or Webpack's auto-imports plugins. The package is currently at version 0.4.0, indicating it is still in active development, with frequent minor releases and bug fixes as seen in recent changelogs. Its primary differentiator is its native integration with the Bun ecosystem, offering potentially faster build times compared to non-Bun specific solutions. It supports features like specifying directories for auto-import detection and ESLint integration. This plugin is crucial for projects leveraging Bun that seek to enhance developer experience and reduce boilerplate code.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure `bun-plugin-auto-imports` in your Bun environment, specifying directories to scan, explicit imports, and generating TypeScript declaration files. It shows the plugin registration using `plugin()` and an example of its options.

import { plugin } from 'bun';
import { autoImports } from 'bun-plugin-auto-imports';
import type { AutoImportsOptions } from 'bun-plugin-auto-imports';

const options: AutoImportsOptions = {
  // Directories to scan for auto-importable modules
  dirs: [
    './src/composables',
    './src/utils',
  ],
  // Optional: Explicitly define global imports (e.g., from npm packages)
  imports: [
    { name: 'z', from: 'zod' }, // Auto-import 'z' from 'zod'
    { name: 'cn', from: 'classnames' }, // Auto-import 'cn' from 'classnames'
  ],
  // Generate a TypeScript declaration file for auto-imports
  dts: './auto-imports.d.ts',
  // Enable ESLint integration (as noted in features)
  eslint: {
    enabled: true,
    filepath: './.eslintrc-auto-imports.json',
  },
};

// Register the plugin globally for runtime or bundler usage
plugin(autoImports(options));

// Example source file: src/utils/formatters.ts
export function formatCurrency(amount: number) {
  return `$${amount.toFixed(2)}`;
}

// Example source file: src/app.ts
// In src/app.ts, you can now use formatCurrency without an explicit import:
// console.log('Starting application...');
// const price = 123.456;
// console.log(`Formatted price: ${formatCurrency(price)}`);

// To build with this plugin configuration (e.g., in bun.config.ts for build command):
// export default {
//   plugins: [
//     autoImports(options)
//   ],
// };

console.log('Bun auto-imports plugin configured. Check auto-imports.d.ts for types.');

view raw JSON →