Module
Module
A file-level unit grouping related code. Used via import/export. Code reuse.
Module
A file-level unit grouping related code. Used via import/export. Code reuse.
A module is a unit that encapsulates related code, functions, classes, variables, and so on into a single file or logical unit. The core purposes of a module are code reusability and encapsulation. By separating the interface to be exposed externally (export) from the internal implementation, other code can use the module's functionality through the defined API alone, without knowing the details of the module's implementation.
The JavaScript module system has a complicated history. Early JavaScript had no concept of modules, and with the emergence of Node.js, CommonJS (require/module.exports) became the server-side standard. In browsers, AMD (Asynchronous Module Definition), which supports asynchronous loading, was used. In 2015, ES Modules (import/export) were adopted as a standard in ES6, and as a result, a unified module system can now be used in both browsers and Node.js.
Modularization offers advantages in several aspects of software development. In terms of maintainability, because each module is independent, it minimizes the impact that modifying a specific feature has on other parts. In terms of testing, individual modules can be isolated for easy unit testing, and dependencies can be replaced with mocks. In terms of collaboration, team members can develop different modules in parallel, which improves productivity.
In practice, the Barrel Pattern and circular dependency management are important. The barrel pattern is a technique that simplifies import paths by re-exporting multiple modules through an index.js file. A circular dependency occurs when module A references B and B references A, and it can cause runtime errors or unpredictable behavior, so it must be resolved by organizing the dependency direction into one direction or by separating out a common module.
// ===== ES Modules (import/export) =====
// math.js - Named Export
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
// calculator.js - Default Export
export default class Calculator {
constructor() {
this.history = [];
}
calculate(operation, a, b) {
const result = operation(a, b);
this.history.push({ a, b, result });
return result;
}
}
// utils/index.js - 배럴 패턴 (Barrel Pattern)
// 여러 모듈을 하나의 진입점으로 재내보내기
export { add, multiply, PI } from './math.js';
export { default as Calculator } from './calculator.js';
export { formatNumber } from './format.js';
// app.js - 다양한 import 방식
// Named import
import { add, multiply, PI } from './utils/index.js';
// Default import
import Calculator from './calculator.js';
// Namespace import (모든 export를 객체로)
import * as MathUtils from './math.js';
// Rename import (별칭 사용)
import { add as addNumbers } from './math.js';
// 동적 import (코드 분할, 조건부 로딩)
async function loadFeature() {
if (needsAdvancedMath) {
const { advancedCalculate } = await import('./advanced-math.js');
return advancedCalculate(data);
}
}
// 사용 예시
const calc = new Calculator();
console.log(calc.calculate(add, 5, 3)); // 8
console.log(calc.calculate(multiply, 4, 7)); // 28
console.log(`원주율: ${PI}`); // 원주율: 3.14159
console.log(MathUtils.add(10, 20)); // 30
"This service logic has become too bloated. I think we should separate it into modules by domain. If we split it into a user module, an order module, and a payment module, and pull the common utilities out into a shared module, each team can develop independently, and it will also be easier to transition to microservices later."
"There's a circular dependency between userService and orderService here. userService calls orderService, and orderService also calls userService. We need to either separate the logic that both services commonly need into a separate userOrderResolver module, or change them to communicate in an event-driven way."
"The bundle size is over 2MB. Don't import all of lodash; import only the functions you need individually from lodash-es so that Tree Shaking works properly. And let's switch this chart library to a dynamic import and exclude it from the initial load."
"Please explain the difference between ES Modules and CommonJS. ES Modules allow static analysis, so Tree Shaking works, and they also support asynchronous loading and Top-level await. CommonJS allows dynamic require, but bundle optimization is difficult. In new projects, I use ES Modules and set 'type': 'module' in package.json. If a CommonJS library is needed in a Node.js environment, I maintain compatibility with createRequire."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
When module A references B and B references A, undefined errors or unpredictable behavior occur depending on the initialization order. Detect circular dependencies with tools such as ESLint's import/no-cycle rule or madge, and organize the dependency direction into a single direction.
Importing an entire library like import _ from 'lodash' includes even unused code in the bundle. Use named imports to bring in only what you need, as in import { debounce } from 'lodash-es', or use babel-plugin-lodash for automatic optimization.
CommonJS (require) makes Tree Shaking difficult because of its dynamic nature. Use ES Modules, and set "sideEffects": false in package.json so that the bundler can safely remove unused code.
A good module has high cohesion (related functionality is grouped together) and low coupling (few dependencies on other modules). If a single module takes on too many roles or depends on too many external modules, consider separating it.