Modules

A note about terminology:It’s important to note that in TypeScript 1.5, the nomenclature has changed.“Internal modules” are now “namespaces”.“External modules” are now simply “modules”, as to align with ECMAScript 2015’s terminology, (namely that module X { is equivalent to the now-preferred namespace X {).

Introduction

Starting with ECMAScript 2015, JavaScript has a concept of modules. TypeScript shares this concept.

Modules are executed within their own scope, not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms.Conversely, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms.

Modules are declarative; the relationships between modules are specified in terms of imports and exports at the file level.

Modules import one another using a module loader.At runtime the module loader is responsible for locating and executing all dependencies of a module before executing it.Well-known module loaders used in JavaScript are Node.js’s loader for CommonJS modules and the RequireJS loader for AMD modules in Web applications.

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module.Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

Export

Exporting a declaration

Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword.

StringValidator.ts
  1. export interface StringValidator {
  2. isAcceptable(s: string): boolean;
  3. }
ZipCodeValidator.ts
  1. import { StringValidator } from "./StringValidator";
  2. export const numberRegexp = /^[0-9]+$/;
  3. export class ZipCodeValidator implements StringValidator {
  4. isAcceptable(s: string) {
  5. return s.length === 5 && numberRegexp.test(s);
  6. }
  7. }

Export statements

Export statements are handy when exports need to be renamed for consumers, so the above example can be written as:

  1. class ZipCodeValidator implements StringValidator {
  2. isAcceptable(s: string) {
  3. return s.length === 5 && numberRegexp.test(s);
  4. }
  5. }
  6. export { ZipCodeValidator };
  7. export { ZipCodeValidator as mainValidator };

Re-exports

Often modules extend other modules, and partially expose some of their features.A re-export does not import it locally, or introduce a local variable.

ParseIntBasedZipCodeValidator.ts
  1. export class ParseIntBasedZipCodeValidator {
  2. isAcceptable(s: string) {
  3. return s.length === 5 && parseInt(s).toString() === s;
  4. }
  5. }
  6. // Export original validator but rename it
  7. export {ZipCodeValidator as RegExpBasedZipCodeValidator} from "./ZipCodeValidator";

Optionally, a module can wrap one or more modules and combine all their exports using export * from "module" syntax.

AllValidators.ts
  1. export * from "./StringValidator"; // exports 'StringValidator' interface
  2. export * from "./ZipCodeValidator"; // exports 'ZipCodeValidator' and const 'numberRegexp' class
  3. export * from "./ParseIntBasedZipCodeValidator"; // exports the 'ParseIntBasedZipCodeValidator' class
  4. // and re-exports 'RegExpBasedZipCodeValidator' as alias
  5. // of the 'ZipCodeValidator' class from 'ZipCodeValidator.ts'
  6. // module.

Import

Importing is just about as easy as exporting from a module.Importing an exported declaration is done through using one of the import forms below:

Import a single export from a module

  1. import { ZipCodeValidator } from "./ZipCodeValidator";
  2. let myValidator = new ZipCodeValidator();

imports can also be renamed

  1. import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
  2. let myValidator = new ZCV();

Import the entire module into a single variable, and use it to access the module exports

  1. import * as validator from "./ZipCodeValidator";
  2. let myValidator = new validator.ZipCodeValidator();

Import a module for side-effects only

Though not recommended practice, some modules set up some global state that can be used by other modules.These modules may not have any exports, or the consumer is not interested in any of their exports.To import these modules, use:

  1. import "./my-module.js";

Default exports

Each module can optionally export a default export.Default exports are marked with the keyword default; and there can only be one default export per module.default exports are imported using a different import form.

default exports are really handy.For instance, a library like jQuery might have a default export of jQuery or $, which we’d probably also import under the name $ or jQuery.

JQuery.d.ts
  1. declare let $: JQuery;
  2. export default $;
App.ts
  1. import $ from "jquery";
  2. $("button.continue").html( "Next Step..." );

Classes and function declarations can be authored directly as default exports.Default export class and function declaration names are optional.

ZipCodeValidator.ts
  1. export default class ZipCodeValidator {
  2. static numberRegexp = /^[0-9]+$/;
  3. isAcceptable(s: string) {
  4. return s.length === 5 && ZipCodeValidator.numberRegexp.test(s);
  5. }
  6. }
Test.ts
  1. import validator from "./ZipCodeValidator";
  2. let myValidator = new validator();

or

StaticZipCodeValidator.ts
  1. const numberRegexp = /^[0-9]+$/;
  2. export default function (s: string) {
  3. return s.length === 5 && numberRegexp.test(s);
  4. }
Test.ts
  1. import validate from "./StaticZipCodeValidator";
  2. let strings = ["Hello", "98052", "101"];
  3. // Use function validate
  4. strings.forEach(s => {
  5. console.log(`"${s}" ${validate(s) ? "matches" : "does not match"}`);
  6. });

default exports can also be just values:

OneTwoThree.ts
  1. export default "123";
Log.ts
  1. import num from "./OneTwoThree";
  2. console.log(num); // "123"

export = and import = require()

Both CommonJS and AMD generally have the concept of an exports object which contains all exports from a module.

They also support replacing the exports object with a custom single object.Default exports are meant to act as a replacement for this behavior; however, the two are incompatible.TypeScript supports export = to model the traditional CommonJS and AMD workflow.

The export = syntax specifies a single object that is exported from the module.This can be a class, interface, namespace, function, or enum.

When exporting a module using export =, TypeScript-specific import module = require("module") must be used to import the module.

ZipCodeValidator.ts
  1. let numberRegexp = /^[0-9]+$/;
  2. class ZipCodeValidator {
  3. isAcceptable(s: string) {
  4. return s.length === 5 && numberRegexp.test(s);
  5. }
  6. }
  7. export = ZipCodeValidator;
Test.ts
  1. import zip = require("./ZipCodeValidator");
  2. // Some samples to try
  3. let strings = ["Hello", "98052", "101"];
  4. // Validators to use
  5. let validator = new zip();
  6. // Show whether each string passed each validator
  7. strings.forEach(s => {
  8. console.log(`"${ s }" - ${ validator.isAcceptable(s) ? "matches" : "does not match" }`);
  9. });

Code Generation for Modules

Depending on the module target specified during compilation, the compiler will generate appropriate code for Node.js (CommonJS), require.js (AMD), UMD, SystemJS, or ECMAScript 2015 native modules (ES6) module-loading systems.For more information on what the define, require and register calls in the generated code do, consult the documentation for each module loader.

This simple example shows how the names used during importing and exporting get translated into the module loading code.

SimpleModule.ts
  1. import m = require("mod");
  2. export let t = m.something + 1;
AMD / RequireJS SimpleModule.js
  1. define(["require", "exports", "./mod"], function (require, exports, mod_1) {
  2. exports.t = mod_1.something + 1;
  3. });
CommonJS / Node SimpleModule.js
  1. var mod_1 = require("./mod");
  2. exports.t = mod_1.something + 1;
UMD SimpleModule.js
  1. (function (factory) {
  2. if (typeof module === "object" && typeof module.exports === "object") {
  3. var v = factory(require, exports); if (v !== undefined) module.exports = v;
  4. }
  5. else if (typeof define === "function" && define.amd) {
  6. define(["require", "exports", "./mod"], factory);
  7. }
  8. })(function (require, exports) {
  9. var mod_1 = require("./mod");
  10. exports.t = mod_1.something + 1;
  11. });
System SimpleModule.js
  1. System.register(["./mod"], function(exports_1) {
  2. var mod_1;
  3. var t;
  4. return {
  5. setters:[
  6. function (mod_1_1) {
  7. mod_1 = mod_1_1;
  8. }],
  9. execute: function() {
  10. exports_1("t", t = mod_1.something + 1);
  11. }
  12. }
  13. });
Native ECMAScript 2015 modules SimpleModule.js
  1. import { something } from "./mod";
  2. export var t = something + 1;

Simple Example

Below, we’ve consolidated the Validator implementations used in previous examples to only export a single named export from each module.

To compile, we must specify a module target on the command line. For Node.js, use —module commonjs;for require.js, use —module amd. For example:

  1. tsc --module commonjs Test.ts

When compiled, each module will become a separate .js file.As with reference tags, the compiler will follow import statements to compile dependent files.

Validation.ts
  1. export interface StringValidator {
  2. isAcceptable(s: string): boolean;
  3. }
LettersOnlyValidator.ts
  1. import { StringValidator } from "./Validation";
  2. const lettersRegexp = /^[A-Za-z]+$/;
  3. export class LettersOnlyValidator implements StringValidator {
  4. isAcceptable(s: string) {
  5. return lettersRegexp.test(s);
  6. }
  7. }
ZipCodeValidator.ts
  1. import { StringValidator } from "./Validation";
  2. const numberRegexp = /^[0-9]+$/;
  3. export class ZipCodeValidator implements StringValidator {
  4. isAcceptable(s: string) {
  5. return s.length === 5 && numberRegexp.test(s);
  6. }
  7. }
Test.ts
  1. import { StringValidator } from "./Validation";
  2. import { ZipCodeValidator } from "./ZipCodeValidator";
  3. import { LettersOnlyValidator } from "./LettersOnlyValidator";
  4. // Some samples to try
  5. let strings = ["Hello", "98052", "101"];
  6. // Validators to use
  7. let validators: { [s: string]: StringValidator; } = {};
  8. validators["ZIP code"] = new ZipCodeValidator();
  9. validators["Letters only"] = new LettersOnlyValidator();
  10. // Show whether each string passed each validator
  11. strings.forEach(s => {
  12. for (let name in validators) {
  13. console.log(`"${ s }" - ${ validators[name].isAcceptable(s) ? "matches" : "does not match" } ${ name }`);
  14. }
  15. });

Optional Module Loading and Other Advanced Loading Scenarios

In some cases, you may want to only load a module under some conditions.In TypeScript, we can use the pattern shown below to implement this and other advanced loading scenarios to directly invoke the module loaders without losing type safety.

The compiler detects whether each module is used in the emitted JavaScript.If a module identifier is only ever used as part of a type annotations and never as an expression, then no require call is emitted for that module.This elision of unused references is a good performance optimization, and also allows for optional loading of those modules.

The core idea of the pattern is that the import id = require("…") statement gives us access to the types exposed by the module.The module loader is invoked (through require) dynamically, as shown in the if blocks below.This leverages the reference-elision optimization so that the module is only loaded when needed.For this pattern to work, it’s important that the symbol defined via an import is only used in type positions (i.e. never in a position that would be emitted into the JavaScript).

To maintain type safety, we can use the typeof keyword.The typeof keyword, when used in a type position, produces the type of a value, in this case the type of the module.

Dynamic Module Loading in Node.js
  1. declare function require(moduleName: string): any;
  2. import { ZipCodeValidator as Zip } from "./ZipCodeValidator";
  3. if (needZipValidation) {
  4. let ZipCodeValidator: typeof Zip = require("./ZipCodeValidator");
  5. let validator = new ZipCodeValidator();
  6. if (validator.isAcceptable("...")) { /* ... */ }
  7. }
Sample: Dynamic Module Loading in require.js
  1. declare function require(moduleNames: string[], onLoad: (...args: any[]) => void): void;
  2. import * as Zip from "./ZipCodeValidator";
  3. if (needZipValidation) {
  4. require(["./ZipCodeValidator"], (ZipCodeValidator: typeof Zip) => {
  5. let validator = new ZipCodeValidator.ZipCodeValidator();
  6. if (validator.isAcceptable("...")) { /* ... */ }
  7. });
  8. }
Sample: Dynamic Module Loading in System.js
  1. declare const System: any;
  2. import { ZipCodeValidator as Zip } from "./ZipCodeValidator";
  3. if (needZipValidation) {
  4. System.import("./ZipCodeValidator").then((ZipCodeValidator: typeof Zip) => {
  5. var x = new ZipCodeValidator();
  6. if (x.isAcceptable("...")) { /* ... */ }
  7. });
  8. }

Working with Other JavaScript Libraries

To describe the shape of libraries not written in TypeScript, we need to declare the API that the library exposes.

We call declarations that don’t define an implementation “ambient”.Typically, these are defined in .d.ts files.If you’re familiar with C/C++, you can think of these as .h files.Let’s look at a few examples.

Ambient Modules

In Node.js, most tasks are accomplished by loading one or more modules.We could define each module in its own .d.ts file with top-level export declarations, but it’s more convenient to write them as one larger .d.ts file.To do so, we use a construct similar to ambient namespaces, but we use the module keyword and the quoted name of the module which will be available to a later import.For example:

node.d.ts (simplified excerpt)
  1. declare module "url" {
  2. export interface Url {
  3. protocol?: string;
  4. hostname?: string;
  5. pathname?: string;
  6. }
  7. export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url;
  8. }
  9. declare module "path" {
  10. export function normalize(p: string): string;
  11. export function join(...paths: any[]): string;
  12. export var sep: string;
  13. }

Now we can /// <reference> node.d.ts and then load the modules using import url = require("url"); or import * as URL from "url".

  1. /// <reference path="node.d.ts"/>
  2. import * as URL from "url";
  3. let myUrl = URL.parse("http://www.typescriptlang.org");

Shorthand ambient modules

If you don’t want to take the time to write out declarations before using a new module, you can use a shorthand declaration to get started quickly.

declarations.d.ts
  1. declare module "hot-new-module";

All imports from a shorthand module will have the any type.

  1. import x, {y} from "hot-new-module";
  2. x(y);

Wildcard module declarations

Some module loaders such as SystemJSand AMD allow non-JavaScript content to be imported.These typically use a prefix or suffix to indicate the special loading semantics.Wildcard module declarations can be used to cover these cases.

  1. declare module "*!text" {
  2. const content: string;
  3. export default content;
  4. }
  5. // Some do it the other way around.
  6. declare module "json!*" {
  7. const value: any;
  8. export default value;
  9. }

Now you can import things that match "!text" or "json!".

  1. import fileContent from "./xyz.txt!text";
  2. import data from "json!http://example.com/data.json";
  3. console.log(data, fileContent);

UMD modules

Some libraries are designed to be used in many module loaders, or with no module loading (global variables).These are known as UMD modules.These libraries can be accessed through either an import or a global variable.For example:

math-lib.d.ts
  1. export function isPrime(x: number): boolean;
  2. export as namespace mathLib;

The library can then be used as an import within modules:

  1. import { isPrime } from "math-lib";
  2. isPrime(2);
  3. mathLib.isPrime(2); // ERROR: can't use the global definition from inside a module

It can also be used as a global variable, but only inside of a script.(A script is a file with no imports or exports.)

  1. mathLib.isPrime(2);

Guidance for structuring modules

Export as close to top-level as possible

Consumers of your module should have as little friction as possible when using things that you export.Adding too many levels of nesting tends to be cumbersome, so think carefully about how you want to structure things.

Exporting a namespace from your module is an example of adding too many layers of nesting.While namespaces sometime have their uses, they add an extra level of indirection when using modules.This can quickly become a pain point for users, and is usually unnecessary.

Static methods on an exported class have a similar problem - the class itself adds a layer of nesting.Unless it increases expressivity or intent in a clearly useful way, consider simply exporting a helper function.

If you’re only exporting a single class or function, use export default

Just as “exporting near the top-level” reduces friction on your module’s consumers, so does introducing a default export.If a module’s primary purpose is to house one specific export, then you should consider exporting it as a default export.This makes both importing and actually using the import a little easier.For example:

MyClass.ts

  1. export default class SomeType {
  2. constructor() { ... }
  3. }

MyFunc.ts

  1. export default function getThing() { return "thing"; }

Consumer.ts

  1. import t from "./MyClass";
  2. import f from "./MyFunc";
  3. let x = new t();
  4. console.log(f());

This is optimal for consumers. They can name your type whatever they want (t in this case) and don’t have to do any excessive dotting to find your objects.

If you’re exporting multiple objects, put them all at top-level

MyThings.ts

  1. export class SomeType { /* ... */ }
  2. export function someFunc() { /* ... */ }

Conversely when importing:

Explicitly list imported names

Consumer.ts

  1. import { SomeType, someFunc } from "./MyThings";
  2. let x = new SomeType();
  3. let y = someFunc();

Use the namespace import pattern if you’re importing a large number of things

MyLargeModule.ts

  1. export class Dog { ... }
  2. export class Cat { ... }
  3. export class Tree { ... }
  4. export class Flower { ... }

Consumer.ts

  1. import * as myLargeModule from "./MyLargeModule.ts";
  2. let x = new myLargeModule.Dog();

Re-export to extend

Often you will need to extend functionality on a module.A common JS pattern is to augment the original object with extensions, similar to how JQuery extensions work.As we’ve mentioned before, modules do not merge like global namespace objects would.The recommended solution is to not mutate the original object, but rather export a new entity that provides the new functionality.

Consider a simple calculator implementation defined in module Calculator.ts.The module also exports a helper function to test the calculator functionality by passing a list of input strings and writing the result at the end.

Calculator.ts

  1. export class Calculator {
  2. private current = 0;
  3. private memory = 0;
  4. private operator: string;
  5. protected processDigit(digit: string, currentValue: number) {
  6. if (digit >= "0" && digit <= "9") {
  7. return currentValue * 10 + (digit.charCodeAt(0) - "0".charCodeAt(0));
  8. }
  9. }
  10. protected processOperator(operator: string) {
  11. if (["+", "-", "*", "/"].indexOf(operator) >= 0) {
  12. return operator;
  13. }
  14. }
  15. protected evaluateOperator(operator: string, left: number, right: number): number {
  16. switch (this.operator) {
  17. case "+": return left + right;
  18. case "-": return left - right;
  19. case "*": return left * right;
  20. case "/": return left / right;
  21. }
  22. }
  23. private evaluate() {
  24. if (this.operator) {
  25. this.memory = this.evaluateOperator(this.operator, this.memory, this.current);
  26. }
  27. else {
  28. this.memory = this.current;
  29. }
  30. this.current = 0;
  31. }
  32. public handleChar(char: string) {
  33. if (char === "=") {
  34. this.evaluate();
  35. return;
  36. }
  37. else {
  38. let value = this.processDigit(char, this.current);
  39. if (value !== undefined) {
  40. this.current = value;
  41. return;
  42. }
  43. else {
  44. let value = this.processOperator(char);
  45. if (value !== undefined) {
  46. this.evaluate();
  47. this.operator = value;
  48. return;
  49. }
  50. }
  51. }
  52. throw new Error(`Unsupported input: '${char}'`);
  53. }
  54. public getResult() {
  55. return this.memory;
  56. }
  57. }
  58. export function test(c: Calculator, input: string) {
  59. for (let i = 0; i < input.length; i++) {
  60. c.handleChar(input[i]);
  61. }
  62. console.log(`result of '${input}' is '${c.getResult()}'`);
  63. }

Here is a simple test for the calculator using the exposed test function.

TestCalculator.ts

  1. import { Calculator, test } from "./Calculator";
  2. let c = new Calculator();
  3. test(c, "1+2*33/11="); // prints 9

Now to extend this to add support for input with numbers in bases other than 10, let’s create ProgrammerCalculator.ts

ProgrammerCalculator.ts

  1. import { Calculator } from "./Calculator";
  2. class ProgrammerCalculator extends Calculator {
  3. static digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
  4. constructor(public base: number) {
  5. super();
  6. const maxBase = ProgrammerCalculator.digits.length;
  7. if (base <= 0 || base > maxBase) {
  8. throw new Error(`base has to be within 0 to ${maxBase} inclusive.`);
  9. }
  10. }
  11. protected processDigit(digit: string, currentValue: number) {
  12. if (ProgrammerCalculator.digits.indexOf(digit) >= 0) {
  13. return currentValue * this.base + ProgrammerCalculator.digits.indexOf(digit);
  14. }
  15. }
  16. }
  17. // Export the new extended calculator as Calculator
  18. export { ProgrammerCalculator as Calculator };
  19. // Also, export the helper function
  20. export { test } from "./Calculator";

The new module ProgrammerCalculator exports an API shape similar to that of the original Calculator module, but does not augment any objects in the original module.Here is a test for our ProgrammerCalculator class:

TestProgrammerCalculator.ts

  1. import { Calculator, test } from "./ProgrammerCalculator";
  2. let c = new Calculator(2);
  3. test(c, "001+010="); // prints 3

Do not use namespaces in modules

When first moving to a module-based organization, a common tendency is to wrap exports in an additional layer of namespaces.Modules have their own scope, and only exported declarations are visible from outside the module.With this in mind, namespace provide very little, if any, value when working with modules.

On the organization front, namespaces are handy for grouping together logically-related objects and types in the global scope.For example, in C#, you’re going to find all the collection types in System.Collections.By organizing our types into hierarchical namespaces, we provide a good “discovery” experience for users of those types.Modules, on the other hand, are already present in a file system, necessarily.We have to resolve them by path and filename, so there’s a logical organization scheme for us to use.We can have a /collections/generic/ folder with a list module in it.

Namespaces are important to avoid naming collisions in the global scope.For example, you might have My.Application.Customer.AddForm and My.Application.Order.AddForm – two types with the same name, but a different namespace.This, however, is not an issue with modules.Within a module, there’s no plausible reason to have two objects with the same name.From the consumption side, the consumer of any given module gets to pick the name that they will use to refer to the module, so accidental naming conflicts are impossible.

For more discussion about modules and namespaces see Namespaces and Modules.

Red Flags

All of the following are red flags for module structuring. Double-check that you’re not trying to namespace your external modules if any of these apply to your files:

  • A file whose only top-level declaration is export namespace Foo { … } (remove Foo and move everything ‘up’ a level)
  • Multiple files that have the same export namespace Foo { at top-level (don’t think that these are going to combine into one Foo!)