Skip to content

Mini Module System

Medium ~50 min

What you'll build

A mini module system with define(name, deps, factory) and require(name) that resolves dependencies, caches modules, and supports circular dependency detection.

Goals

  • Implement a module registry (Map of name → module)
  • Resolve dependencies recursively before executing factory
  • Cache modules so factories run only once
  • Detect and report circular dependencies

Prerequisites

  • Functions and closures
  • Objects and Maps
  • Recursion

Steps

  1. 1

    Design the API

    Decide on the API: define(name, deps, factory) registers a module; require(name) returns its exports. Document how deps are resolved (each dep is required before factory runs). Acceptance: define + require work for a single module with no deps.

  2. 2

    Implement the registry and define

    Keep a Map of modules. define stores { deps, factory, exports: undefined, executed: false }. Acceptance: after define, the module is in the registry but not yet executed.

  3. 3

    Implement require with dependency resolution

    require(name): if the module is executed, return its exports. Otherwise, require each dep recursively, then call factory(...depExports), store the result, mark executed, and return. Acceptance: a module with deps gets them resolved in order.

  4. 4

    Add circular dependency detection

    Track a set of modules currently being resolved. If require is called for a module already in the set, throw a circular dependency error. Acceptance: A requires B requires A throws a clear error.

  5. 5

    Test with a dependency graph

    Define three modules: math (no deps), calc (deps: [math]), app (deps: [calc, math]). Require app and verify all factories ran once in the right order. Then test a circular case (A→B→A) and confirm it throws.

Try it yourself

What you learned

You built the core of a module system — understanding this demystifies how import/export, require, and bundlers like webpack/rollup resolve dependencies and handle cycles.

Related Resources

Related Lessons

  • Modules

    ES modules and CommonJS use this resolution pattern.

  • Functions

    Factories are functions that produce module exports.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic