4.8 Importing ES6 modules

Just like we did with the external legacy modules we can also import ES6 modules. Let’s learn how to we can do it.

Getting Ready

All you need to implement in this recipe is an installation of TypeScript version 2.0 or higher.

How to do it

The import statement for ES6 looks as follows:

import arrays from './arrays';

How it works

As we can see in the preceding code snippet, this statement is really similar to the one that we used in the recipes about legacy external modules earlier in this chapter. The main difference is that, instead of invoking the require function and assigning its return value to a variable named arrays, in this case, we are using the reserved keyword “from”.

Note that the preceding import statement will import only the element flagged as default in the imported module.

There’s more

It is also possible to import multiple elements from a module that has multiple exports using curly brackets:

import { arrays1, arrays2 } from './arrays'; 

We can also import the default export of a module together with some non-default ones:

import arrays, { arrays1, arrays2 } from './arrays';

The preceding line of code imports the default export of the arrays module and stores into a variable named arrays. It then non-default imports the array1 and array2 imports. We can also create aliases for a module when importing it by using an asterisk:

import * as arraysAlias from './arrays'; 

The preceding line of code imports both, the default export and the non-default exports of the arrays module and stores them as properties of the arraysAlias alias. Aliases can also be applied to one element rather than the entire module:

import { arrays1 as arr1, arrays2 as arr2 } from './arrays'; 

See also

Please refer to the recipes about the declaration of ES6 modules and the recipes about external legacy modules to gain a better understanding about the TypeScript external modules landscape.

Please note that the default export statements like the following:

export default arrays;

Should be thought of as exporting a member on the module named default. ES6 modules understand how to handle default exports, which means that the following ES6 statement:

import arrays from './arrays';

Will import the arrays object. However, legacy external modules don’t understand how to manage default exports automatically. This means that the preceding statement is not semantically equivalent to the following legacy external modules statement:

import arrays = require('./arrays')

Which will import an object with a property named default and arrays as its values:

{ default: arrays }

Shiv Kushwaha

Author/Programmer