4.20 Running SystemJS modules with SystemJS

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

Getting Ready

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

How to do it

To use SystemJS we need to import three JavaScript files:

  • The SystemJS library
  • The SystemJS configuration
  • The application’s root module So you should have something like the following in your HTML page:
    <script src="../../node_modules/systemjs/dist/system.js"></script>
    <script src="../../src/module_loaders/systemjs/system.config.js"></script>
    <script src="../../src/module_loaders/systemjs/app.js"></script>
    The following code snippet showcase a basic SystemJS configuration file:
    System.config({
    baseURL: '../../src/module_definitions/run_time/external',
    packages: {
      'systemjs': {
        map: {
          './systemjs/arrays' : 'arrays.js',
          './systemjs/collections' : 'collections.js',
          './systemjs/functions' : 'functions.js',
          './systemjs/objects' : 'objects.js',
          './systemjs/utility' : 'utility.js'
        }
      }
    }
    });
    

    How it works

    The applications root module in the companion source code looks as follows:

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

    The root module uses the import function to load two dependency (ndrscr). As we can see, SystemJS modules are loaded asynchronously. We didn’t have to use the full path of the ndrscr file because we configured the base URL:

    baseURL: '../../src/module_definitions/run_time/external'
    

    We also declared some mappings for some folders to ensure that SystemJS is able to find the requested modules: ```ts ‘systemjs’: { map: { ‘./systemjs/arrays’ : ‘arrays.js’, ‘./systemjs/collections’ : ‘collections.js’, ‘./systemjs/functions’ : ‘functions.js’, ‘./systemjs/objects’ : ‘objects.js’, ‘./systemjs/utility’ : ‘utility.js’ } }

```
There are many options options available but unfortunately, it is impossible to cover all of theme in this book.

Please refer to https://github.com/systemjs/systemjs/blob/master/docs/import-maps.md to learn more about the available SystemJS configuration options.

Source Code

Running SystemJS modules with SystemJS

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

Author/Programmer