Understanding import and export in TypeScript and ES6 (ECMAScript 2015)

As you may know ES6 has introduced import and export statements that helps you work easily with modular pattern. TypeScript is subset of ES6 so we also can use import and export with TypeScript.

Note: This feature is only beginning to be implemented in browsers natively at this time. It is implemented in many transpilers, such as the Traceur Compiler, Babel, Rollup, and Webpack.

Let's try it now. I'm going to create simply calculator module with multiply, plus and minus functions, then export them.

calculator.ts

export function multiply(a: number, b: number) {  
    return a * b;
}

export function plus(a: number, b: number) {  
    return a + b;
}

export function minus(a: number, b: number) {  
    return a - b;
}

As you can see in the code, we are exporting multiply, plus and minus functions by using export statement. Beside functions, we also can export interface, class, object and primitives.

Now, I'm going to import and use them in app.ts.

app.ts

import { multiply, plus, minus } from './calculator';

var a = 10;  
var b = 5;

console.log(`${a} * ${b} = ${multiply(a, b)}`);  
console.log(`${a} + ${b} = ${plus(a, b)}`);  
console.log(`${a} - ${b} = ${minus(a, b)}`);  

multiply, plus and minus functions are imported in app.ts by using import statement. Now they're available to use. If you are new with Template literals ${variable}, read more detail here.

There are few more options with import and export. You can see here:

import defaultMember from "module-name"; import * as name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import defaultMember, { member [ , [...] ] } from "module-name";
import defaultMember, * as name from "module-name";
import "module-name";

Check out this document for more information.

As I said earlier, import and export cannot use in browser at this time, maybe future it do. So we have to use a module loader to make it work on browser. There are many module loaders, in this post I use Webpack.

You can get the source code on Github and run by yourself.

Hope you enjoy this post and get the idea of import and export.

Checkout more TypeScript posts.

Nguyen Tran

I'm Nguyen, a full stack web passion for frontend and love Angular.

Subscribe to Nguyen Tran

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!