Using EcmaScript 2015 Modules in TypeScript with SystemJS

TypeScript and SystemJS header

There are two powerful tools for Angular developers in TypeScript and SystemJS. They are both in the Angular 2 quick start and they work just as well with AngularJS 1.x for building maintainable Angular applications.

However, getting started using these tools can be tricky. You need to align both tools' configurations so they work together and having a basic understanding of what happens under the hood can save you hours of confusion and frustration. Once you understand the core concepts and setup the configuration, this workflow helps to make your code more decoupled and maintainable – and maybe even more fun.

This post walks through the basics of using SystemJS and TypeScript in Visual Studio for development. You learn the minimum configuration that matters, how it interacts with the rest of the system, and what to expect when compiling and running your application.

Before You Begin

If you want to skip right to the code, it is all on GitHub. The example is in Visual Studio 2015 (there's a free community edition) and is designed to run with minimal dependencies.

The example project is a component called ListMaker which allows the user to make a list by typing in a textbox and pressing ENTER. This component is made up of two child components AddItemTextbox and List, and includes basic CSS styles. The main script bootstraps the ListMaker component and everything is brought together in index.html.

Application structure

SystemJS is the only library used in the example. Adding dependencies with TypeScript and SystemJS, including Angular, is another level of complexity that is omitted here intentionally. There are enough pieces to understand using SystemJS and TypeScript together so watch for more posts on this topic.

Required Tools and Frameworks

This walkthrough uses the following tools and frameworks:

Visual Studio

The demo is built using Visual Studio 2015 Community. Visual Studio provides a seamless experience to compile and run your application on a development server. It also has first class support for TypeScript.

TypeScript Add-In for Visual Studio

This add-in enables TypeScript support in Visual Studio. The demo uses TypeScript 1.8.36. Install the add-in through Visual Studio's Extensions and Updates manager or from the web.

SystemJS

SystemJS is the JavaScript module loader. It's included in the project on GitHub. You can also obtain it from your favorite JavaScript package manager or as a release download from GitHub.

If you don't use Visual Studio, don't fret. You can port the code to another web project as there are no Visual Studio-specific dependencies. Be sure you know how to setup a development server and TypeScript support in your environment of choice.

Workflow Overview

When using these tools together, your workflow requires a compilation step. The Visual Studio TypeScript add-in automatically handles the compilation when you build or run your project. If you aren't in the habit of using front-end compilation tools such as TypeScript, this may be new to you. Here is an overview:

Diagram of TypeScript with SystemJS workflow

TypeScript Configuration

While the default TypeScript configuration in Visual Studio works, there are a couple options to discuss. First, you should consider adding a tsconfig.json file to your project. By default, you find the TypeScript properties in the Visual Studio project properties, however using a tsconfig.json file has advantages.

Most importantly, the project properties do not show all of the options that are available in tsconfig.json so if at some point you want to set other options, you will be limited by the tooling in the project properties. Also, the tsconfig.json file is a standard configuration for every editor and compiler that supports TypeScript. Therfore if someone joins your team that knows TypeScript, they will know where to look for the configuration no matter which tools they use.

Note: you should install the latest update of Visual Studio 2015. Earlier versions did not properly recognize the tsconfig.json file.

The first related configuration option is compilerOption.module. This option sets which module loader format the TypeScript compiler emits. Because SystemJS understands all of them, it's hard to pick the wrong one. Ultimately your choice here may depend on the other tooling you use for building your JavaScript. For now, choose "system" as it is the native format of the loader but you may find that "amd" provides greater compatibility with other compilation tools.

The other option is compilerOption.target. This option sets which version of the ECMAScript® standard to target when generating JavaScript from your TypeScript files. This value largely depends on which browsers you are targeting. The default value is "es3" which gives you the broadest range of browser support. It's worth noting that should you eventually want to emit native ECMAScript module syntax, this option will need to be set to "es2015".

Your tsconfig.json file should at least have:

Implement ECMAScript 2015 Module Syntax

Take a look at the ListMaker component without the ECMAScript 2015 module syntax:

The first thing to note is that ListMaker is in the global scope as it is meant to be re-used within a given application. The ListMaker implementation, however, is not in global scope and is instead wrapped in an immediately invoked function expression (IIFE). If you look closely, you also see that ListMaker depends on two other constructor functions not defined in this code: AddItemTextBox and List. These constructors are also defined in global scope and furthermore you have to ensure that AddItemTextBox and List are loaded in the browser before trying to create a ListMaker.

The fundamental mechanism for modules are import and export statements. The import statements define the module's dependencies and the export statements define the objects that are available to other modules. Take a look at how the ListMaker code changes when using ECMAScript modules:

The module's dependencies are clearly defined in the import statment and you can easily determine where to obtain the source code for these objects looking at its URL. Also, because module scope is separated from global scope by default, the use of an IIFE is unnecessary leading to less code and more readable code.

Finally notice the export statement and the use of the default keyword. While ECMAScript modules can define multiple exports, only one object is defined as the default export. Similarly, the import statements for this module are explicitly importing the default export from the target modules.

This post doesn't go into all the ways you can write your import and export statements. TypeScript supports various options for writing these definitions so read more about them here.

SystemJS Configuration and Reconciling Import URLs

This is likely the most important part configuring SystemJS and TypeScript to work together. Both SystemJS and TypeScript evaluate the import statements. When TypeScript looks at the import statement, it is looking for a TypeScript file so that the compiler can use the types defined in that file. Using import './Foo', TypeScript looks in the current directory for Foo.ts and then uses the information contained in that file for compilation and type checking.

SystemJS on the other hand looks at import './Foo' and then attempts to make a request to the server for <current-directory>/Foo and without any special configuration, this request will produce a 404 resource not found error. What SystemJS needs to request instead is <current-directory>/Foo.js.

Luckily, SystemJS has a configuration option to append a file extension to requests. You configure this by setting up a specific path in your application using the packages option. In the demo, all of the TypeScript files are in the components folder and SystemJS needs to add a .js extension to these requests.

Create a systemjs.config.js file in your application and add the following configuration:

You can optionally configure this behavior for the whole application by using an empty string '' to set the root of your application as the path. Also remember this configuration only applies to requests made by SystemJS and other requests still require explicit file extensions. There are many useful options in the SystemJS configuration so be sure to read up on its capabilities.

Bootstrap the Application

There is bootstrapping logic for the application in main.ts. The browser requests this file first and the script's purpose is to access the Document Object Model (DOM) and render the root component which in this case is ListMaker. It's important to understand using module loaders that the first module retrieved is the last one to execute its contents. For example, even though main.ts is the entry point of the application, all of the other dependent scripts execute prior to main.ts executing.

Once you determine the main script, you bring the configuration and bootstrapping together on the root HTML page. Reference SystemJS, followed by the SystemJS configuration, and then use the System.import syntax from SystemJS to load the post-compiled version of main, 'scripts/main'. Remember that even though the extension is not present, you have configured SystemJS to add the extension and request scripts/main.js.

Once main.js is loaded, all of the other import statements are evaluated and the target modules are loaded as well to compose the application. This diagram illustrates the dependencies and the order of execution when loading.

Diagram illustrating bootstrap process

At this point, you have configured enough for your application to run. Remember to compile the TypeScript first and all of the modules will run and execute in the correct order. Be sure to check out the complete project for all of the details.

Only the Beginning

This is the first step using ECMAScript 2015 modules with SystemJS and TypeScript and this workflow works quite well as a development workflow. Once you understand the configuration and basics of using the tools, you can get up and running rather quickly.

But you need more. As an Angular developer, you need to bring in third-party libraries and seamlessly integrate with your application code. This is the topic of the next post in this series.

At some point, you will want to bundle these scripts together into one request. You may even want to create several bundles that are loaded dynamically via a route change or a certain screen size. The good news is that by separating your code into modules that have explicit dependency references, you have made this configuration much easier to attain.

Finally, the documentation for both of these tools is well done. Be sure to read the TypeScript documentation and the SystemJS documentation for more information.

Stay tuned for more on this topic. If there is anything else you want to know about these tools or if you also have experience with them, please share in the comments below.

2 thoughts on “Using EcmaScript 2015 Modules in TypeScript with SystemJS”

    1. Good point. I plan to do a lot more with Angular 2 and TypeScript so we’re building towards that. You’ve got me thinking about some other configurations for this, though. Thanks again for the last minute QA on the post ;).

Leave a Reply

Your email address will not be published. Required fields are marked *