JavaScript has two module systems: CommonJS (CJS) and ECMAScript Modules (ESM). They differ in more than syntax, and those differences carry consequences for how a project is built, bundled, and maintained.
Modules are not merely a mechanism for splitting code across files. They are the primary means of drawing boundaries between parts of a system, and each import, export, or new module shapes the architecture, whether or not the developer intends it. Without guiding principles, even a large codebase built on modules can become hard to maintain.
How ESM Differs From CommonJS
CommonJS came first, designed for server-side JavaScript. Its syntax (require(), module.exports) was never natively supported by browsers. Because the import mechanism is a function, require() is not restricted to the top of a file; it can appear inside an if statement or a loop.
// CommonJS — require() is a function call, can appear anywhere
const module = require('./module')
// this is valid CommonJS — the dependency is conditional and unknowable until runtime
if (process.env.NODE_ENV === 'production') {
const logger = require('./productionLogger')
}
// the path itself can be dynamic — no static tool can resolve this
const plugin = require(`./plugins/${pluginName}`)
ESM does not allow this. An import statement has to sit at the top of the module, and anything else is invalid syntax.
// ESM — import is a declaration, not a function call
import { formatDate } from './formatters'
// invalid ESM — imports must be at the top level, not conditional
if (process.env.NODE_ENV === 'production') {
import { logger } from './productionLogger' // SyntaxError
}
// the path must be a static string — no dynamic resolution
import { plugin } from `./plugins/${pluginName}` // SyntaxError: : template literals are dynamic paths
That restriction is deliberate, and it comes down to static analysis and tree-shaking. With CommonJS, static tools cannot determine which modules a program needs at runtime, so when a bundler is unsure whether a module is required, it includes it by default. ESM was designed to fix this: by confining imports to the top of the file and requiring paths to be static string literals, tools can understand the dependency structure ahead of time, eliminate unused modules, and produce smaller bundles.
Setting Rules for Module Dependencies
Clean architecture is a debated methodology and not appropriate for every team; for small projects it can amount to over-engineering. But when a project has no strict structural rules, it offers a reasonable starting point. Its central constraint, Robert Martin's dependency rule, states:
"Nothing in an inner circle can know anything at all about something in an outer circle."
The application is divided into layers, with business logic at the core and frameworks and drivers at the outermost edge, and interface adapters and business rules in between.

Dependencies must point inward. Framework and driver code may depend on interface adapters, adapters on use cases, and use cases on entities — never the reverse. The practical value is isolation from volatility: technologies change far more often than business rules, and business logic should not have to change every time the stack does. Build the project around the business logic, not around the tools.
Without such a rule, imports tend to be made freely from anywhere, and as the project grows, changes become increasingly difficult until a refactor becomes unavoidable.
Reading the Module Graph
The module graph, which records how modules depend on one another, makes the resulting architecture visible. A healthy graph has dependencies flowing in a single direction, with high-level modules depending on low-level ones and never the opposite.

An unhealthy graph looks quite different.

Here utils.js is a dependency of many modules — more than in the healthy graph — and also depends on request.js and view.js. That spread increases the blast radius of any fault in utils.js and makes the module harder to test. Its dependency on request.js is a second problem: it breaks the ideal flow, since a low-level module is depending on a higher-level one.
Both issues trace back to utils.js doing too much. Applying the Single Responsibility Principle, everything the file does can be inventoried, and each cohesive piece of functionality extracted into its own focused module, reducing the number of modules that depend on any single utility.
The same graph also shows two circular dependencies:
express.js→application.js→view.js→express.jsresponse.js→utils.js→view.js→response.js
Circular dependencies occur when modules directly or indirectly depend on each other. They make modules hard to reuse, and a change to any module in the cycle is likely to affect the others: in the first cycle, a break in view.js breaks application.js, which in turn breaks express.js.
Madge and Dependency Cruiser can help inspect and manage the graph. Madge visualizes module dependencies; Dependency Cruiser goes further, letting you set rules about which layers may import from which others. Understanding the graph also helps with build-time optimization and with fixing problems such as circular dependencies and high coupling.
The Barrel File Trade-off
A barrel file — usually named something like index.js or index.ts — re-exports components from other files, giving consumers a cleaner import path. The pattern is straightforward to illustrate. Given a set of component files:
// auth/login.ts
export function login(email: string, password: string) {
return `Logging in ${email}`;
}
// auth/register.ts
export function register(email: string, password: string) {
return `Registering ${email}`;
}
imports without a barrel look like this:
// somewhere else in the app
import { login } from '@/features/auth/login';
import { register } from '@/features/auth/register';
The number of import lines grows with the number of modules a file needs. With a barrel, the same imports collapse to:
// somewhere else in the app
import { login, register } from '@/features/auth';
and the barrel handling the exports looks like this:
// auth/index.ts
export * from './login';
export * from './register';
Barrel files improve readability and ease refactoring by reducing the import lines you manage. The cost is performance: build times lengthen, and tree-shaking becomes less effective, so bundles grow larger. Atlassian reported 75% faster builds and a slight reduction in JavaScript bundle size after removing barrel files from the front-end of its Jira application. Barrel files suit small projects; at larger scale they buy readability at the expense of performance.
Coupling to Avoid
Coupling describes how components rely on each other, and it cannot be eliminated — parts of a system must interact to function. Two kinds should be avoided. Tight coupling exists when a dependent module relies on implementation details of its dependency, making it hard or impossible to change the dependency without touching the dependent module; heavily coupled projects can see one update cascade into changes across several modules, a phenomenon known as change amplification. Implicit coupling occurs when one module secretly depends on another, often through global singletons, shared mutable state, or side effects; it can defeat tree-shaking and produce unexpected behavior that is difficult to trace.
In practice, that means not exposing a module's implementation details for others to depend on, keeping inter-module dependencies explicit, and using patterns such as shared mutable state and global singletons with care.
Ownership and Module Boundaries
In large applications, different modules are usually assigned to different teams, and the resulting boundaries tend to fall into one of three kinds:
- Weak: outsiders may change code that isn't assigned to them, while the responsible team monitors and maintains it.
- Strong: ownership is fixed and changes to someone else's code go through its owner.
- Collective: no one owns anything, and anyone may change any part of the project.
Whatever the arrangement, communication is unavoidable. Conway's Law offers a lens on how that plays out:
Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization's communication structure.
From this, several assumptions follow:
| Good Communication | Poor Communication | |
|---|---|---|
| Weak Code Ownership | Architecture may still emerge, but boundaries remain unclear | Fragmented, inconsistent architecture |
| Strong Code Ownership | Clear, cohesive architecture aligned with ownership boundaries | Disconnected modules; integration mismatches |
| Collective Code Ownership | Highly collaborative, integrated architecture | Blurred boundaries; architectural drift |
One rule is worth carrying into every boundary decision: modules that frequently change together should share the same boundary, because shared evolution is a strong signal that they form a single cohesive unit.
Starting With an Existing Codebase
Structuring a large project is more than arranging files and folders: it means drawing boundaries through modules and coupling them into a working system, deliberately rather than by accident. On an existing codebase, start by installing Madge or Dependency Cruiser and pointing Madge at the project. Look at the graph for circular dependencies and for modules that receive arrows from everywhere, and ask whether what you see matches what you planned. From there, enforce boundaries, break circular chains, move modules, and extract utilities — incrementally rather than in one large refactor.



