History of modules

In the early days of JavaScript, when the language only ran in browsers, there were no modules, but it was still possible to split the JavaScript for a web page into multiple files by using multiple script tags in HTML:

<html>
<head>
<script src="a.js">script>
<script src="b.js">script>
head>
<body>body>
html>

This approach had some downsides, especially as web pages grew larger and more complex. In particular, any script loaded onto the same page can read and write from a shared set of variables and functions — appropriately called the “global scope” - meaning the scripts had to be very careful not to overwrite anything from other scripts.

Any system that solves this problem by giving files their own scope, while still providing a way to make bits of code available to other files, can be called a "module system."

There are many module systems, and TypeScript supports emitting several, but this documentation will focus on the two most important systems today: ECMAScript modules (ESM) and CommonJS (CJS).

ECMAScript

CommonJS

CommonJS (CJS) is the module system that originally shipped in Node.js, before ESM was part of the language specification. It's still supported in Node.js alongside ESM. It uses plain JavaScript objects and functions named exports and require:

Loading TypeScript...

Was this page helpful?