Lazy Require

Defer a require until the first call that needs it, and cache what comes back.

Two modules that need each other cannot both finish loading first: the second one to be entered sees a half-built module.exports from the first, and reads whatever happened to be assigned by then. Deferring the require moves it to call time, when both modules have finished loading, so the second sees the whole thing.

The argument is a function rather than a path, so the require inside it resolves against the calling file. A path string would resolve against this module instead, and every relative path from anywhere else in the tree would be wrong.

b.lazyRequire(loader) #

stable0.1.29

Answer a getter that calls loader the first time it is called and answers the same value every time after. The getter carries reset(), which drops the cached value so the next call loads again; a test that swaps a module out calls it in teardown.

loader is a function that performs the require and returns it, so the path inside resolves against the calling file. A value that is not a function throws here rather than at the first use.

var b = require("@blamejs/core");
var db = b.lazyRequire(function () { return require("./db"); });
db().from("users");   // the first call loads and caches
db.reset();           // teardown

Last updated 2026-10-12T14:21:56.879Z by seeder.