ES6 Modules

TypeScript 1.5 supports ECMAScript 6 (ES6) modules. ES6 modules are effectively TypeScript external modules with a new syntax: ES6 modules are separately loaded source files that possibly import other modules and provide a number of externally accessible exports. ES6 modules feature several new export and import declarations. It is recommended that TypeScript libraries and applications be updated to use the new syntax, but this is not a requirement. The new ES6 module syntax coexists with TypeScript’s original internal and external module constructs and the constructs can be mixed and matched at will.

Export Declarations

In addition to the existing TypeScript support for decorating declarations with export, module members can also be exported using separate export declarations, optionally specifying different names for exports using as clauses.

  1. interface Stream { ... }
  2. function writeToStream(stream: Stream, data: string) { ... }
  3. export { Stream, writeToStream as write }; // writeToStream exported as write

Import declarations, as well, can optionally use as clauses to specify different local names for the imports. For example:

  1. import { read, write, standardOutput as stdout } from "./inout";
  2. var s = read(stdout);
  3. write(stdout, s);

As an alternative to individual imports, a namespace import can be used to import an entire module:

  1. import * as io from "./inout";
  2. var s = io.read(io.standardOutput);
  3. io.write(io.standardOutput, s);

Re-exporting

Using from clause a module can copy the exports of a given module to the current module without introducing local names.

  1. export { read, write, standardOutput as stdout } from "./inout";

export * can be used to re-export all exports of another module. This is useful for creating modules that aggregate the exports of several other modules.

  1. export function transform(s: string): string { ... }
  2. export * from "./mod1";
  3. export * from "./mod2";

Default Export

An export default declaration specifies an expression that becomes the default export of a module:

  1. export default class Greeter {
  2. sayHello() {
  3. console.log("Greetings!");
  4. }
  5. }

Which in turn can be imported using default imports:

  1. import Greeter from "./greeter";
  2. var g = new Greeter();
  3. g.sayHello();

Bare Import

A “bare import” can be used to import a module only for its side-effects.

  1. import "./polyfills";

For more information about module, please see the ES6 module support spec.