Module Introduction

A module is a TypeScript file that has it’s own scope, so that variable inside it aren’t able to be used outside of the file unless the developer imports or exports the file.

History of JavaScript with scoping

In the ye olden days of designing web pages, the landscape was very different when it came to importing out scripts into a web page.

What you would typically do is use the <script> tags so that your HTML would be able to integrate JavaScript into itself, hence, you would have your HTML like the following:

    <script src="apple.js"></script>
    <script src="banana.js"></script>
var greeting = "Hello World!";

The predicament with performing this type of implementation is that the page has the same scope (also known as global scope). This meant that it would be possible for variables and functions of the same name to overwrite each other.

Try the above example locally, and you’ll be shocked to fine that the console.log will be outputting "Hello World!".

Solving the scope

Essentially to solve this issue, we need to give each file it’s own scope and we can do this through the use of modules.

We can create a module through the use of that module systems specific import/export syntax. There are multiple different module systems that currently exist, but the main ones used are ECMAScript Modules (ESM) and CommonJS (CJS).

Below is an example of using ESM:

export default "Hello World!"
import apple from './apple.js"

apple.js exports the text “Hello World!”, you can then import that in banana.js to use the variable. With the use of the export and import keywords, the files are immediately turned to modules and have their own scope.

Note that the keywords in other module systems could be different.