ES6 Modules Overview

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

To learn about ES6 Modules, you have to have Node.js and the typescript compiler tsc installed as described in previous tutorial.  This is because at the time of this writing, browsers have not implemented ES6 modules yet.  So we write ES6 module syntax in Typescript files and have the Typescript compiler along with its default common.js module loader transpile it down to ES5 code.

Let create an lib.ts file containing some utility library functions which we export using the export keyword before each function we want to export…

Library typescript module

Import ES6 Module Syntax

And we have an app.ts file which we import these two functions for use…

import es6 module syntax

Note the import keyword followed by the ES6 destructuring syntax of the curly braces.  Then followed by the path of the module we are importing from.  In this case ‘./lib’.  Note that we don’t include the “.ts” or “.js” file extension on the module.

In ES6 Modules, each file is a single module.  And a module is a single file.

Now that the function computeTax and computeTip have been imported, we can use it as shown above.

To run, we compile with tsc and run with node…

running es6 modules

Import Star As Syntax

Alternatively, you can import everything from a module using import star-as syntax …

import star-as syntax

In which case, you need to precede the function name with the module name you have chosen to import as.

export default syntax

You can mark any one item in the module as export default.  Here we have marked computeTax as the default export …

export default syntax

Now when we import, we can write it without the destructuring curly braces…

import default syntax

But we still need the curly braces for computeTip because that was not marked as default.

Another way to export is to export an entire object like so…

export object

With an import like this …

import object

Alternatively, you can import as a different name …

import as different name

More ES6 features here.