Close

TypeScript - ES6 Modules

[Updated: Dec 21, 2018, Created: Dec 21, 2018]

Following example shows ES6 modules support in TypeScript.

Example

ts-src/lib.ts

//export union type
export type num = number | string;

interface Person {
    name: string,
    age: num
}

interface Contact {
    phone: string;
}

//export intersection type
export type PersonDetails = Person & Contact;

ts-src/lib2.ts

//exporting interface
export interface Employee {
    name: string;
    dept: string;
}

//exporting constant
export const MAX_TASKS: number = 3;

//default export
export default function printDescription() {
    console.log("this is running in a default function");
}

//class without export - will include in export clause below
class Task<T> {
    constructor(private _param: T) {
    }

    run(): void {
        console.log("task running: " + this._param);
    }
}

//enum without export - will include in export clause below
enum HorizontalAlign { LEFT, CENTER, RIGHT }

//export clause
export { HorizontalAlign as Align, Task }


//re-exporting module lib.mjs
export { PersonDetails as PersonType, num as NumType } from "./lib.js";

ts-src/app.ts

import * as miscUtil from "./lib2.js";
import defaultFunction from "./lib2.js";

defaultFunction();
console.log(miscUtil.MAX_TASKS);
let e: miscUtil.Employee = { name: "John", dept: "IT" }
new miscUtil.Task("display employee").run();
let personDetails: miscUtil.PersonType = { name: "Tina", age: 22, phone: "111-111-111" };
console.log(JSON.stringify(personDetails));
console.log(miscUtil.Align[0]);

web-app/index.html

<html>
<script type="module" src="js/app.js"></script>
<body>
<div id="output"></div>
</body>
</html>

Running

To try examples, open the project in VS Code, compile it via tsc and start Live Server (tutorial).

On loading index.html in a web browser, we get following output in console:

this is running in a default function
task running: display employee
{"name":"Tina","age":22,"phone":"111-111-111"}
LEFT

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.2.2
ES6 Modules in TypeScript Select All Download
  • typescript-es6-modules
    • ts-src
      • app.ts
      • web-app

    See Also