A Bun plugin for configurable auto-imports - use libraries globally without import statements.
β¨ New: Automatic TypeScript declarations generation for perfect IDE support!
Want to use functions and libraries without writing import statements? Here's how:
bun install bun-autoimportsCreate 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!
});Create or update bunfig.toml:
preload = ["./plugins/auto-imports.ts"]// 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! π
- π« Zero imports needed - Use libraries directly without import statements
- π― Automatic TypeScript support - Auto-generates
global.d.tsfor perfect IDE intellisense - π Relative paths work - Use
./lib/utilsjust like normal imports - β‘ Fast - No runtime overhead, loads once at startup
- π§ Fully configurable - Choose exactly what you want auto-imported
π Complete Setup Guide
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β 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 importsHow it works: The plugin automatically resolves relative paths against your project directory (process.cwd()), so they work exactly like you'd expect!
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
This is the method shown above - it's the simplest and most reliable.
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();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
"libraryName": "package-name"
// Equivalent to: import libraryName from "package-name"
// Generated type: var libraryName: typeof import("package-name").default;"varName": { from: "package", type: "named", name: "exportName" }
// Equivalent to: import { exportName as varName } from "package"
// Generated type: var varName: typeof import("package").exportName;"varName": { from: "package", type: "namespace" }
// Equivalent to: import * as varName from "package"
// Generated type: var varName: typeof import("package");π― Real-World Examples
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
});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
});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
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")
});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
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
- Check that
bunfig.tomlhas 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
- 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
- Make sure
generateTypes: trueis set in your configuration - Check if
global.d.tswas generated in your project root - Restart your TypeScript language server (in VSCode: Cmd+Shift+P β "TypeScript: Restart TS Server")
- Make sure your
tsconfig.jsonincludes theglobal.d.tsfile
β‘ How It Works
- Bun's preload system loads your plugin before your main code
- The plugin resolves relative paths against your project directory (
process.cwd()) - Libraries are dynamically imported and assigned to
globalThis - TypeScript declarations are automatically generated based on your imports
- Your code can use these globals without import statements
- 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 | |
| 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 | |
| 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 setupOur 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- Zero entry file modifications
- Clean separation of concerns
- Just configure and use
- Perfect relative path support
- Automatic TypeScript declarations
- IDE-friendly with full autocomplete
- 100% Bun native APIs
- No external dependencies
- Optimized for Bun's runtime
- Automatic
global.d.tsgeneration - Perfect IDE integration
- No manual type declarations needed
Use other solutions if:
- You need build-time transformation
- You're already using
unimportecosystem - You prefer explicit plugin registration
π API Reference
The main function for runtime auto-imports.
Parameters:
config?: AutoImportConfig- Configuration object
Returns: Promise<void>
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;
}For build-time usage (advanced).
Parameters:
config?: AutoImportConfig- Configuration object
Returns: BunPlugin