2 Hours

3. Modules: CommonJS vs ES Modules

Modular Design

What is a Module?

A module is simply a file. Every file in Node.js is a module. The important thing is that variables in one file are PRIVATE by default. They cannot be seen by other files unless you explicitly choose to share them.

Why Modules Matter

In a browser, if you write let count = 5 in one script and another script also writes let count = 10, they conflict and overwrite each other. In Node.js, each file is isolated. You can have the same variable name in ten different files without any conflict. This prevents bugs and keeps your code organized.

JavaScript
// file1.js
const name = 'Alice';

// file2.js
const name = 'Bob';  // No conflict with file1.js!

// Each file is its own private universe

CommonJS: The Traditional Way

CommonJS uses require() to import and module.exports to export. This was the original Node.js module system. It is synchronous and works everywhere without configuration. You still see it in many production codebases.

JavaScript
// exporter.js
const greet = (name) => `Hello ${name}`;
module.exports = { greet };

// importer.js
const { greet } = require('./exporter.js');
console.log(greet('World'));
OutputHello World

Try it: Add another function to exporter.js and export it. Import both in importer.js.

ES Modules: The Modern Way

ES Modules use import and export keywords. This is the official JavaScript standard. To use them, set type: module in your package.json or use the .mjs file extension. ES Modules are asynchronous by default and support tree-shaking (removing unused code).

JavaScript
// exporter.mjs
export const greet = (name) => `Hello ${name}`;
export const farewell = (name) => `Goodbye ${name}`;

// importer.mjs
import { greet, farewell } from './exporter.mjs';
console.log(greet('World'));
OutputHello World

Default Exports vs Named Exports

Named exports allow multiple exports per file and require curly braces when importing. Default exports allow only one per file and can be imported with any name. Default exports are often used for the main thing a file exports, like a React component or an Express router.

JavaScript
// Named exports (multiple per file)
export const add = (a,b) => a + b;
export const subtract = (a,b) => a - b;

// Default export (only one per file)
const calculator = { add, subtract };
export default calculator;

// Importing
import calculator, { add } from './math.js';

The package.json File

package.json is the blueprint of your project. It lists your dependencies, defines scripts like npm start, and stores configuration. Without it, npm doesn't know what packages to install or how to run your app.

Text
{
  "name": "my-api",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
  },
  "dependencies": {
    "express": "^4.18.0"
  }
}

Semantic Versioning (SemVer)

Versions follow the pattern MAJOR.MINOR.PATCH (like 4.18.2). PATCH is for bug fixes (safe to update). MINOR is for new features that don't break existing code (safe). MAJOR is for breaking changes (not safe). The ^ symbol means compatible with this major version. ^4.18.0 will update to 4.19.0 but not to 5.0.0.

Text
{
  "dependencies": {
    "express": "^4.18.0",  // Any 4.x.x version
    "lodash": "~4.17.0",   // Only patch updates (4.17.x)
    "moment": "2.29.0"     // Exact version only
  }
}

Knowledge Check

Ready to test your understanding of 3. Modules: CommonJS vs ES Modules?

Back