liveBook · Manning

CommonJS

As explained in Essential TypeScript 5, Third Edition

CommonJS is a JavaScript module system specification for defining and loading modules, especially in server-side environments.

CommonJS is an older JavaScript module specification that became a de facto standard through Node.js support. It divides large applications into manageable files, but ECMAScript modules are preferred when the runtime supports them. section 4.5

Node.js must know which module format to use. Configure the package.json type property as commonjs, or use the relevant file-extension convention described for the project. section 4.5.1

TypeScript compiled to CommonJS

A TypeScript file can export sum and another file can import it. With an ES5 target, the compiler emits CommonJS-style JavaScript using require and exports; Node.js can execute that output. The generated code includes require("./calc") and invokes the exported sum function, producing "Total: 600". section 5.8

Listing 4.25 Setting the module type in the package.json file in the primer folder
{
  "name": "primer",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "nodemon": "^2.0.20"
  },
  "type": "module"
  
}

Inspect the package.json structure used to select a module format; changing its type value to commonjs selects CommonJS handling. section 4.5.1

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains its history, configuration, and TypeScript-generated require output, but does not detail the full CommonJS specification.
Examples
Uses split TypeScript files, an exported sum function, generated require code, package.json settings, and a Total: 600 output.
What it assumes
Assumes JavaScript familiarity while introducing module organization, format selection, and Node.js handling.
What you can do after
Operate/configure Node.js projects by selecting CommonJS and recognizing TypeScript output that uses require and exports.
How it connects
Connects CommonJS with ECMAScript modules, Node.js, TypeScript compiler targets, and package.json configuration.

Also explained in

Compare how 3 books explain CommonJS →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.