Node.js Modules and npm

Understand CommonJS and ES modules, manage dependencies with npm, and publish your own packages to the npm registry.

Node.js has a powerful module system that allows you to organize code and share functionality. npm is the world's largest software registry.

CommonJS vs ES Modules

CommonJS (require/module.exports) is the original Node.js module system. ES Modules (import/export) is the modern standard with static analysis support.

Creating Modules

Organize your code into modules by functionality. Export what other modules need, keep implementation details private.

npm Basics

npm manages dependencies, scripts, and package publishing. The package.json file is the heart of every Node.js project.

Semantic Versioning

npm uses semver for version management. Understanding major.minor.patch helps you manage dependencies safely.

Security

Regularly audit dependencies with npm audit. Be cautious with dependencies - each one is a potential security risk.

Code Examples

CommonJS Modules

commonjs/math.js
// math.js
function add(a, b) {
  return a + b;
}

function multiply(a, b) {
  return a * b;
}

// Export functions
module.exports = { add, multiply };

// Or export individually
// exports.add = add;
// exports.multiply = multiply;

// main.js
const { add, multiply } = require('./math');
const math = require('./math');

console.log(add(2, 3)); // 5
console.log(math.multiply(2, 3)); // 6

ES Modules

esm/utils.mjs
// utils.mjs (or .js with "type": "module" in package.json)
export function formatDate(date) {
  return date.toISOString().split('T')[0];
}

export function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

// Default export
export default class Logger {
  log(message) {
    console.log(`[${formatDate(new Date())}] ${message}`);
  }
}

// main.mjs
import Logger, { formatDate, capitalize } from './utils.mjs';
import * as utils from './utils.mjs';

const logger = new Logger();
logger.log(capitalize('hello'));

Package.json Configuration

package.json
{
  "name": "my-app",
  "version": "1.0.0",
  "type": "module",
  "main": "dist/index.js",
  "scripts": {
    "start": "node dist/index.js",
    "dev": "node --watch src/index.js",
    "build": "tsc",
    "test": "node --test",
    "lint": "eslint src/"
  },
  "dependencies": {
    "express": "^4.18.0"
  },
  "devDependencies": {
    "typescript": "^5.0.0",
    "eslint": "^8.0.0"
  },
  "engines": {
    "node": ">=18.0.0"
  }
}

Frequently Asked Questions

Should I use CommonJS or ES Modules?

For new projects, prefer ES Modules as they're the standard and offer benefits like static analysis and tree-shaking. CommonJS is still fine for existing projects and has broader ecosystem support.

What's the difference between dependencies and devDependencies?

dependencies are required to run your app and installed in production. devDependencies are only needed for development (testing, building) and aren't installed in production with npm install --production.

How do I handle npm security vulnerabilities?

Run npm audit regularly, update vulnerable packages with npm audit fix, and consider using tools like Snyk for continuous monitoring. Review major updates manually as they may contain breaking changes.

Need Node.js Help?

Slashdev.io builds production-ready Node.js applications for businesses of all sizes.

Get in Touch