TypeScript Modules - TypeScript

How Modules are used in Typescript?

Modules are designed to organize code written in TypeScript. Modules are divided roughly :

  • Internal module
  • External module

Internal Module

The internal module includes the old version of Typescript. It is used to group classes, interfaces, and functions into a single unit and can be exported to another module. This logical grouping is called the namespace in the latest version of TypeScript. As a result, the internal module is out of date and you can use namespaces. While still supporting internal modules, it is recommended to use namespaces instead of internal modules.

Internal Module Syntax (Old)

Namespace Syntax (New)

JavaScript generated in both cases are same

External Module

You can specify and load dependencies between multiple external js files using an external module of TypeScript. If only one js file is used, external modules are irrelevant. Historically, dependency management between JavaScript files was done using browser script tags (<script> </ script>). However, this is not extensible because it is very linear when loading the module. In other words, there is not one way to load a file without loading the asynchronous option of the module. There is no script tag when programming js for the server (NodeJs etc.).

There are two scenarios for loading dependents js files from a single main JavaScript file.

  • Client Side : RequireJs
  • Server Side : NodeJs

Selecting a Module Loader

A module loader is required to support loading external JavaScript files. This will be another js library. For browsers, the most common library is RequieJS. This is the implementation of the AMD (Asynchronous Module Definition) specification. AMD can load files one by one, rather than load them separately, even if they are dependent on each other.

Defining External Module

When externalJS or AMD's external module is defined with TypeScript, each file is treated as a module. As a result, internal modules can be used in external modules.

No additional work is required when migrating TypeScript from AMD to the CommonJs module system. The only thing that needs to be changed is that the compiler flag is different from JavaScript by migrating from CommonJs to AMD or vice versa.

The syntax for declaring an external module is using keyword ‘export’ and ‘import’.


To use the declared module in other files, use the import keyword, as shown below. For file names, only the specified extension is used.


An example illustrates teh following.

The command to compile the main TypeScript file for AMD system is as follows.

When compiled, AMD's next JavaScript code is generated.





The command to compile the main TypeScript file for Commonjs systems is

On compiling, it will generate following JavaScript code for Commonjs.





All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

TypeScript Topics