npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

bun-autoimports

v1.0.0

Published

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

Downloads

4

Readme

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

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 {};

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!
    }),
  ],
});

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");

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
});

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 {};

"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
  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

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

vs. stacksjs/bun-plugin-auto-imports

| 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
});

vs. arstnei0/bun-auto-import

| 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

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