Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 39 ยท Runtime Basics

Modules and Imports in Bun

Learn how Bun resolves modules - ES modules and CommonJS side by side, top-level await, import.meta.dir and main, importing JSON and text files, node: and bun: specifiers.

Modules decide how your code is split into files and how those files find each other. Bun supports both module systems that exist in the JavaScript world, ES modules (import/export) and CommonJS (require/module.exports), and lets you mix them in one project. This lesson explains how Bun resolves an import, what import.meta offers, how to import data files, and which special specifiers (node:, bun:) exist.

ES modules are the default

Write standard import and export:

TypeScript
// math.ts
export function add(a: number, b: number): number {
  return a + b;
}

export const PI = 3.14159;

export default function square(n: number): number {
  return n * n;
}
TypeScript
// main.ts
import square, { add, PI } from "./math";

console.log(add(2, 3), square(4), PI);

You can write ./math, ./math.ts or ./math.js: Bun tries the extensions in a sensible order. That differs from plain Node.js ES modules, which require the full extension. The "type": "module" field in package.json is optional for Bun (it understands .mjs, .mts, .cjs and .cts regardless), but the init template sets it for compatibility with other tools.

Top-level await

A module can use await at its top level, without wrapping it in a function:

TypeScript
const response = await fetch("https://example.com/data.json");
const data = await response.json();
console.log(data);

Every module that imports this file waits for it to finish. Use it for start-up work such as reading config or opening a database connection, and avoid it in files that many modules import if the work is slow.

CommonJS works too

Bun runs require and module.exports code without a flag:

JavaScript
// legacy.cjs
module.exports = { greet: (name) => `Hi ${name}` };
JavaScript
const { greet } = require("./legacy.cjs");
console.log(greet("Ada"));

Two interop features save time:

  • You can import a CommonJS file from ESM, and the exports become named imports when Bun can detect them.
  • You can require() an ES module, even one with top-level await in simple cases. (Plain Node.js had to wait years for this.)

Mixing is fine, but pick one style for new code. ES modules give you static analysis, tree shaking when bundling, and top-level await.

Resolution: how Bun finds a module

When you write import x from "something", Bun decides what "something" means in this order:

  1. A relative or absolute path (./a, ../b, /c) is resolved against the importing file, trying .ts, .tsx, .js, .jsx, .json and index files.
  2. A node: or bun: prefix loads a built-in module.
  3. A path alias from tsconfig.json (@/utils) is expanded.
  4. A bare name (zod, @scope/pkg) is looked up in node_modules folders, walking up from the importing file, using the package's exports, module or main fields.
flowchart TD
  A["import 'something'"] --> B{"Starts with ./ ../ or / ?"}
  B -- yes --> C["Resolve relative to this file"]
  B -- no --> D{"node: or bun: ?"}
  D -- yes --> E["Built-in module"]
  D -- no --> F{"Matches tsconfig paths?"}
  F -- yes --> G["Expand alias"]
  F -- no --> H["Search node_modules upward"]

Bun checks the cheapest, most specific rules first and falls back to node_modules.

If nothing matches you get error: Cannot find module 'something' from '/path/main.ts'. The message names both the module and the importing file, which tells you where to look.

Built-in modules: node: and bun:

Node's standard library is available through the node: prefix, which Bun recommends because it can never collide with an npm package:

TypeScript
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { createHash } from "node:crypto";

Bun's own modules use bun::

TypeScript
import { Database } from "bun:sqlite";
import { test, expect } from "bun:test";
import { dlopen, FFIType } from "bun:ffi";

Importing "bun" gives the same Bun object as the global, which is useful when you want explicit imports for readability:

TypeScript
import { file, write, serve } from "bun";

import.meta: facts about the current file

import.meta carries information about the module being run. Bun implements the standard parts and several useful extras:

Property Meaning
import.meta.url file:// URL of the current file
import.meta.path Absolute path of the file
import.meta.dir Absolute path of the file's folder (like __dirname)
import.meta.file The file name only
import.meta.main true when this file is the entry point
import.meta.env Same object as process.env
import.meta.resolve("x") The URL a specifier would resolve to

__dirname and __filename also work in Bun ES modules, so older code runs unchanged.

The import.meta.main flag is the idiomatic replacement for Python's if __name__ == "__main__":

TypeScript
export function run() {
  console.log("doing the work");
}

if (import.meta.main) {
  run(); // only when started with `bun thisfile.ts`
}

This lets one file be both a library and a script. Tests can import run without triggering it.

A stand-in using import.meta

Node 24 provides import.meta.dirname, import.meta.filename and import.meta.url. This stand-in shows how a file can discover its own location and decide whether it is the entry point:

Node.js Stand-in: import.meta basics (runs on Node 24)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

On real Bun, import.meta.main is simply true for the entry file and false for everything it imports.

Importing data files

Bun parses certain file types at import time, so you can treat data as modules:

TypeScript
import pkg from "./package.json";
import settings from "./settings.toml";
import notes from "./notes.txt" with { type: "text" };
import logo from "./logo.png"; // path string by default (bundler loader "file")

console.log(pkg.version);
console.log(settings.server.port);
console.log(notes.length);
  • JSON and TOML become plain JavaScript objects.
  • Adding with { type: "text" } loads any file as a string.
  • Images and other binary files import as a file path (when bundled) so you can reference them in HTML.

These are the same loaders the bundler uses; the loaders lesson lists them all.

Dynamic imports

import() loads a module on demand and returns a promise. Use it to split rarely needed code, or to pick a module by name:

TypeScript
const lang = process.env.LANG?.startsWith("fr") ? "fr" : "en";
const { messages } = await import(`./i18n/${lang}.ts`);
console.log(messages.hello);

Dynamic imports run on demand and are cached: a second import() of the same file returns the same module instance.

Circular imports and caching

Each module is evaluated once and its exports are cached. If a.ts imports b.ts and b.ts imports a.ts, Bun gives b.ts the partially initialised exports of a.ts, so top-level code that uses them too early sees undefined (or a ReferenceError for let/const bindings in the temporal dead zone). Fix cycles by moving shared code to a third file.

Node.js Stand-in: module cache and live bindings (runs on Node 24)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

bump() changes a let export and both importers see the new value: ES module exports are live bindings, not copies.

Common mistakes

  • Using require of an ES module that has top-level await in complex cases: prefer import().
  • Writing import json from "./x.json" without resolveJsonModule and then fighting the editor.
  • Assuming __dirname exists in code that also runs in browsers.
  • Importing Node built-ins without the node: prefix: it works, but the prefix is clearer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which property tells you whether the current file is the program's entry point in Bun?

    import.meta.main is true for the entry file only, like Python's main check.
  2. 2. How do you import Bun's SQLite module?

    Bun's own built-in modules use the bun: prefix.
  3. 3. In what order does Bun treat an import like "zod"?

    Bare names resolve through tsconfig paths and then node_modules folders walking upward.
  4. 4. What is true of ES module exports?

    Imports see the current value of an exported binding, so changes made by the exporting module are visible.

Summary

  • Bun supports ES modules and CommonJS and lets you mix them; imports may omit file extensions.
  • Top-level await works in any ES module.
  • Resolution order: relative paths, node:/bun: built-ins, tsconfig aliases, then node_modules.
  • import.meta.dir, .file, .path, .url and .main describe the current file; import.meta.main marks the entry point.
  • JSON, TOML and text files can be imported directly; modules are evaluated once and cached.

Next: Environment Variables and Configuration