Node.js Modules
Modules define boundaries. In Node, the choice between CommonJS and ES modules affects syntax, tooling, and interop.
CommonJS
const path = require("node:path");
module.exports = { path };
ES modules
import path from "node:path";
export function joinPath() {
return path.join("a", "b");
}
Design rules
- Export only the names you want other files to depend on.
- Use one module style per project unless you have a migration reason.
- Keep file boundaries aligned with business boundaries when possible.
Practice
- Create one file that exports a helper function.
- Import it from another file and call it once.
- Record how module boundaries reduced coupling.