Modules in TypeScript

Learn how to create, export, and import modules in TypeScript to modularize and structure our codebase.

Introduction to modules in TypeScript

Modularization is a popular technique used in programming languages that allows programs to be built from a series of smaller libraries or modules. This technique is also applied to object-oriented code bases, where each class is typically housed in its own file. When referencing classes that exist in another source file, we need a mechanism for the TypeScript compiler, as well as the JavaScript runtime, to be able to locate the class that we are referencing. This is where modules are used.

TypeScript has adopted the module syntax that is part of ES2015. This means that we can use this syntax when working with modules, and the compiler will generate the relevant JavaScript to support modules based on the target JavaScript version we have selected. There is no change in syntax, and there is no change in our code in order to support earlier versions of the JavaScript runtime.

Exporting modules

There are two things that we need in order to write and use modules.

Firstly, a module needs to expose something to the outside world in order for it to be consumed. This is called exporting a symbol from a module and uses the TypeScript keyword export.

As an example of this, suppose we create a source directory named modules, and within this modules directory, a file name Module1.ts containing the following code:

Get hands-on with 1400+ tech skills courses.