ES6 Modules Overview

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…

Import ES6 Module Syntax

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

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…

Import Star As Syntax

Alternatively, you can import everything from a module using 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 …

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

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