Mini Module System
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
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.
Hint
Look at AMD (require.js) and CommonJS for inspiration — your mini system is a simplified AMD.
- 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.
Hint
Don't run the factory in define — defer execution to require for lazy loading.
- 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.
Hint
Pass the dep exports as arguments to the factory, like AMD: factory.apply(null, depExports).
- 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.
Hint
Use a module-scoped Set (not on the instance) so it resets per top-level require but persists through the recursion.
- 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.
Hint
Log inside each factory to confirm execution order: math first, then calc, then app.
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
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.