Skip to content

eduwass/bun-autoimports

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

14 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Bun Auto-Imports Plugin

A Bun plugin for configurable auto-imports - use libraries globally without import statements.

✨ New: Automatic TypeScript declarations generation for perfect IDE support!

πŸš€ Quick Start

Want to use functions and libraries without writing import statements? Here's how:

1. Install

bun install bun-autoimports

2. Create Plugin Configuration

Create plugins/auto-imports.ts:

import { loadAutoImports } from "bun-autoimports";

await loadAutoImports({
  imports: {
    // Your libraries here - examples:
    "_": "lodash",           // npm packages
    "dayjs": "dayjs",        // npm packages
    
    // Local modules work with relative paths!
    "myUtils": { from: "./lib/utils", type: "namespace" },
  },
  verbose: true,
  generateTypes: true, // 🎯 Auto-generates global.d.ts for perfect IDE support!
});

3. Configure Bun Preload

Create or update bunfig.toml:

preload = ["./plugins/auto-imports.ts"]

4. Use Without Imports!

// No import statements needed!
console.log(_.chunk([1, 2, 3, 4], 2)); // [[1, 2], [3, 4]]
console.log(dayjs().format('YYYY-MM-DD')); // 2024-01-01
console.log(myUtils.someFunction()); // From your local module!

// πŸŽ‰ Your IDE knows about all these globals with full type checking!

That's it! πŸŽ‰

✨ Key Features

  • 🚫 Zero imports needed - Use libraries directly without import statements
  • 🎯 Automatic TypeScript support - Auto-generates global.d.ts for perfect IDE intellisense
  • πŸ“ Relative paths work - Use ./lib/utils just like normal imports
  • ⚑ Fast - No runtime overhead, loads once at startup
  • πŸ”§ Fully configurable - Choose exactly what you want auto-imported

πŸ“– Documentation

πŸ“– Complete Setup Guide

For NPM Packages

This is the easiest and most common use case:

// plugins/auto-imports.ts
import { loadAutoImports } from "bun-autoimports";

await loadAutoImports({
  imports: {
    // Default imports (most common)
    "_": "lodash",
    "axios": "axios", 
    "dayjs": "dayjs",
    
    // Named imports
    "Database": { 
      from: "bun:sqlite", 
      type: "named", 
      name: "Database" 
    },
    
    // Namespace imports
    "fs": { from: "node:fs", type: "namespace" },
    "path": { from: "node:path", type: "namespace" },
  },
  verbose: true,
  generateTypes: true, // 🎯 Enable automatic TypeScript declarations
});

Important: Make sure to install the packages first:

bun install lodash axios dayjs

For Local Modules

βœ… Relative paths work perfectly! Use them just like regular imports:

// βœ… All of these work great!
"myFunction": { 
  from: "./lib/myFunction",  // Relative paths work!
  type: "named", 
  name: "myFunction" 
}

"utils": { 
  from: "./utils/index",     // Also works!
  type: "namespace" 
}

"helper": "./helpers/format"  // Shorthand for default imports

How it works: The plugin automatically resolves relative paths against your project directory (process.cwd()), so they work exactly like you'd expect!

Complete Working Example

Here's a full example that actually works:

Project structure:

my-project/
β”œβ”€β”€ lib/
β”‚   └── utils.ts          # export const greet = (name) => `Hello ${name}!`
β”œβ”€β”€ plugins/
β”‚   └── auto-imports.ts   # Plugin configuration
β”œβ”€β”€ bunfig.toml          # Bun configuration  
β”œβ”€β”€ index.ts             # Your main code (no imports needed!)
β”œβ”€β”€ global.d.ts          # 🎯 Auto-generated TypeScript declarations
└── package.json

plugins/auto-imports.ts:

import { loadAutoImports } from "bun-autoimports";

await loadAutoImports({
  imports: {
    // NPM packages (install first: bun install lodash)
    "_": "lodash",
    
    // Local functions (relative paths work!)
    "greet": { 
      from: "./lib/utils", 
      type: "named", 
      name: "greet" 
    },
  },
  verbose: true,
  generateTypes: true, // 🎯 This creates global.d.ts automatically!
});

bunfig.toml:

preload = ["./plugins/auto-imports.ts"]

index.ts:

// No imports needed! Everything is global with full type checking:

console.log(greet("World"));           // From local module
console.log(_.camelCase("hello-world")); // From lodash

// πŸŽ‰ Your IDE shows autocomplete, type hints, and error checking!

global.d.ts (auto-generated):

// Auto-generated global type declarations for bun-autoimports
// This file is automatically updated when your auto-imports configuration changes

declare global {
  var _: typeof import("lodash").default;
  var greet: typeof import("./lib/utils").greet;
}

export {};
πŸ”§ Alternative Methods

Method 1: Runtime Loading (⭐ Recommended)

This is the method shown above - it's the simplest and most reliable.

Method 2: Direct Function Call

For programmatic usage:

import { loadAutoImports } from "bun-autoimports";

// Configure and load
await loadAutoImports({
  imports: {
    "myLib": "my-library",
    "myUtils": "./utils", // Relative paths work here too!
  },
  generateTypes: true, // 🎯 Enable TypeScript generation
});

// Now use without imports
myLib.doSomething();
myUtils.helper();

Method 3: Build-time Plugin

For bundling applications (advanced):

import autoImportsPlugin from "bun-autoimports";

await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
  plugins: [
    autoImportsPlugin({
      imports: { 
        "myLib": "my-library",
        "utils": "./src/utils" // Relative paths work in build-time too!
      },
      generateTypes: true, // 🎯 Works in build-time too!
    }),
  ],
});
πŸ“ Import Types Reference

Default Import

"libraryName": "package-name"
// Equivalent to: import libraryName from "package-name"
// Generated type: var libraryName: typeof import("package-name").default;

Named Import

"varName": { from: "package", type: "named", name: "exportName" }
// Equivalent to: import { exportName as varName } from "package"
// Generated type: var varName: typeof import("package").exportName;

Namespace Import

"varName": { from: "package", type: "namespace" }
// Equivalent to: import * as varName from "package"
// Generated type: var varName: typeof import("package");
🎯 Real-World Examples

React Development

import { loadAutoImports } from "bun-autoimports";

await loadAutoImports({
  imports: {
    "React": "react",
    "useState": { from: "react", type: "named", name: "useState" },
    "useEffect": { from: "react", type: "named", name: "useEffect" },
    
    // Your custom hooks with relative paths!
    "useAuth": { from: "./hooks/useAuth", type: "default" },
  },
  generateTypes: true, // 🎯 Perfect IDE support for React development
});

Backend Development

import { loadAutoImports } from "bun-autoimports";

await loadAutoImports({
  imports: {
    "_": "lodash",
    "axios": "axios",
    "Database": { from: "bun:sqlite", type: "named", name: "Database" },
    "fs": { from: "node:fs", type: "namespace" },
    
    // Your database models and utilities
    "User": { from: "./models/User", type: "default" },
    "dbUtils": { from: "./utils/database", type: "namespace" },
  },
  generateTypes: true, // 🎯 Full type safety for backend development
});

Utility Functions

import { loadAutoImports } from "bun-autoimports";

await loadAutoImports({
  imports: {
    // Local utilities with clean relative paths!
    "formatDate": { 
      from: "./utils/date", 
      type: "named", 
      name: "formatDate" 
    },
    "validateEmail": { 
      from: "./utils/validation", 
      type: "named", 
      name: "validateEmail" 
    },
    // Or import entire utility modules
    "mathUtils": { from: "./utils/math", type: "namespace" },
  },
  generateTypes: true, // 🎯 IDE knows about all your utility functions
});
🎯 TypeScript Configuration

Automatic Type Generation (⭐ Recommended)

The plugin automatically generates global.d.ts with perfect type declarations:

await loadAutoImports({
  imports: {
    "_": "lodash",
    "myUtils": "./lib/utils",
  },
  generateTypes: true,     // Enable auto-generation (default: true)
  typesPath: "./global.d.ts", // Where to save types (default: "./global.d.ts")
});

Manual Type Declarations

If you prefer manual control, you can disable auto-generation:

await loadAutoImports({
  imports: {
    "_": "lodash",
    "myUtils": "./lib/utils",
  },
  generateTypes: false, // Disable auto-generation
});

Then create your own global.d.ts:

declare global {
  var _: typeof import("lodash").default;
  var myUtils: typeof import("./lib/utils");
}

export {};
πŸ› Troubleshooting

"Cannot find module" errors

For NPM packages:

  • Make sure the package is installed: bun install package-name
  • Check the package name is correct

For local modules:

  • Use relative paths like "./lib/myModule" or "../utils/helper"
  • Make sure the file exists and exports the function
  • Double-check the export name matches your configuration
  • Absolute paths still work if you prefer them

"ReferenceError: X is not defined"

  • Check that bunfig.toml has the preload configuration
  • Verify the plugin file is in the correct location
  • Make sure there are no syntax errors in your plugin file
  • Check the console for error messages with verbose: true

Import not working

  • Restart your Bun process after changing the configuration
  • Check the verbose output to see what's being loaded
  • Verify the import type (default/named/namespace) is correct

TypeScript/IDE issues

  • Make sure generateTypes: true is set in your configuration
  • Check if global.d.ts was generated in your project root
  • Restart your TypeScript language server (in VSCode: Cmd+Shift+P β†’ "TypeScript: Restart TS Server")
  • Make sure your tsconfig.json includes the global.d.ts file
⚑ How It Works
  1. Bun's preload system loads your plugin before your main code
  2. The plugin resolves relative paths against your project directory (process.cwd())
  3. Libraries are dynamically imported and assigned to globalThis
  4. TypeScript declarations are automatically generated based on your imports
  5. Your code can use these globals without import statements
  6. Your IDE gets perfect type information and autocomplete
πŸ”„ How This Compares to Other Solutions

There are other auto-import solutions for Bun, but this plugin takes a different approach:

Feature bun-autoimports (this plugin) stacksjs/bun-plugin-auto-imports
Approach ⚑ Runtime - Uses Bun's preload system πŸ”¨ Build-time - Uses Bun's bundler plugins
Setup πŸ“ Configure bunfig.toml only πŸ’» Register plugin in entry file code
Dependencies 🎯 Zero dependencies - Pure Bun native πŸ“¦ Depends on unimport library
TypeScript πŸ€– Auto-generates global.d.ts βœ‹ Manual TypeScript declarations
Path Support βœ… Relative paths work out of the box ⚠️ More complex path handling
API Used πŸš€ 100% Bun native APIs πŸ”— Mix of Bun + external libraries
Performance ⚑ Runtime loading, no build step πŸ”¨ Build-time transformation

Example comparison:

stacksjs approach:

// You must modify your entry file
import { plugin } from 'bun'
import { autoImports } from 'bun-plugin-auto-imports'

plugin(autoImports({
  presets: ['solid-js'],
  imports: [{ name: 'z', from: 'zod' }],
  dts: './src/auto-import.d.ts',
}))

Our approach:

// plugins/auto-imports.ts (separate file)
import { loadAutoImports } from "bun-autoimports";

await loadAutoImports({
  imports: {
    "z": "zod",
    "myUtils": "./lib/utils", // Relative paths work!
  },
  generateTypes: true, // Auto-generates TypeScript declarations
});
Feature bun-autoimports (this plugin) arstnei0/bun-auto-import
Setup Complexity 🟒 Simple - Configure once in bunfig.toml 🟑 Moderate - Plugin registration required
Entry File βœ… No changes needed to entry file ❌ Must modify entry file with plugin code
Dependencies 🎯 Zero dependencies πŸ“¦ Depends on unimport
TypeScript πŸ€– Automatic - Generates global.d.ts βœ‹ Manual TypeScript setup
Local Modules πŸ›€οΈ Relative paths supported ⚠️ More complex for local modules
Configuration πŸ“ Separate plugin file (clean) πŸ’» Mixed with application code

Example comparison:

arstnei0 approach:

// Must be in your entry file
import { plugin } from "bun"

plugin(
  (await import("bun-auto-import")).autoImport({
    presets: ["solid-js"],
    imports: [{ name: "z", from: "zod" }],
    dts: `./src/auto-import.d.ts`,
  })
)

// Your app code mixed with plugin setup

Our approach:

# bunfig.toml (clean separation)
preload = ["./plugins/auto-imports.ts"]
// Your entry file stays clean - no plugin code needed!
// Just use the globals directly:
console.log(z.string().parse("hello")); // z is globally available

🎯 Why Choose This Plugin?

βœ… For Maximum Simplicity

  • Zero entry file modifications
  • Clean separation of concerns
  • Just configure and use

βœ… For Local Development

  • Perfect relative path support
  • Automatic TypeScript declarations
  • IDE-friendly with full autocomplete

βœ… For Pure Bun Experience

  • 100% Bun native APIs
  • No external dependencies
  • Optimized for Bun's runtime

βœ… For TypeScript Projects

  • Automatic global.d.ts generation
  • Perfect IDE integration
  • No manual type declarations needed

Use other solutions if:

  • You need build-time transformation
  • You're already using unimport ecosystem
  • You prefer explicit plugin registration
πŸ“š API Reference

loadAutoImports(config?)

The main function for runtime auto-imports.

Parameters:

  • config?: AutoImportConfig - Configuration object

Returns: Promise<void>

AutoImportConfig

interface AutoImportConfig {
  imports?: Record<string, string | ImportConfig>;
  verbose?: boolean;
  generateTypes?: boolean; // Auto-generate global.d.ts (default: true)
  typesPath?: string;      // Where to save types (default: "./global.d.ts")
}

interface ImportConfig {
  from: string;
  type?: 'default' | 'namespace' | 'named';
  name?: string;
}

autoImportsPlugin(config?)

For build-time usage (advanced).

Parameters:

  • config?: AutoImportConfig - Configuration object

Returns: BunPlugin

About

A Bun plugin for configurable auto-imports - use libraries globally without import statements.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published