4.19 Importing SystemJS modules

In the preceding recipe we learned how to declare SystemJS modules in this chapter we will learn how to import SystemJS modules.

Getting Ready

All you need to implement this recipe is an installation of TypeScript version 2.0 or higher, Gulp, SystemJS and the gulp-typescript plugin.

How to do it

We can import a AMD module using a function named import:

System.import('systemjs/ndrscr.js').then(function (_) {

    const result1 = _.arrays.first([5, 4, 3, 2, 1], 3);

    const result2 = _.arrays.last([5, 4, 3, 2, 1], 3);
    // ...


How it works

The import function is defined by the SystemJS module loader and takes one argument:

  • The path or name of the module that we which to import. As we can see in the preceding code snippet, we can change the name of the modules when they are passed to the callback function. For example, we changed ndrscr to underscore (_). The import function returns a promise. A promise is an object that allow us to request a value in an asynchronous way. In this case we will try to access the imported module. If the importing is successful, the promise object will invoke the callback passed to the then method:
    System.import('systemjs/ndrscr.js').then(function(_) { //…

    We can also indicate a callback to be invoked if the import operation fails:

    .then(function(_) { /*...*/ })
    .catch(function{ console.log(import failed!); });

Source Code

Importing SystemJS modules

See also

Please refer to the recipes about ES6 modules to learn about the declaration of external modules. Refer to chapter one to learn more about Gulp.

Shiv Kushwaha