Include External JavaScript Libraries In An Angular 2 TypeScript Project

I’ve been a JavaScript developer for a while now, but with the release of Angular 2, I’ve been inspired to pick up TypeScript. However, what happens when I want to use one of my hundreds of available external JavaScript libraries in my project?

I’m going to share how to use your favorite JavaScript libraries in a TypeScript Angular 2 application.

UPDATE 03/06/2017: Want an updated, more thorough set of instructions for using JavaScript libraries in your TypeScript application? Check out this revisited article I wrote on the subject. The information below is still valuable and worth a read regardless.

As of right now Angular 2 is in its first beta stage, but breaking changes shouldn’t be introduced (per the Angular 2 developers) so any stable release should be fine.

Before we look at a very functional project, let’s discuss the few small things that makes this possible.

To include a JavaScript library in your TypeScript application you must first include it in your HTML file as a script tag. To use the library you must add the following to one of your ts files:

declare var libraryVar: any;

Replace libraryVar with a variable, function, or class within your JavaScript library. At this point it is ready for use.

Because it can be a little tricky to grasp, we’re going to make a full project to demonstrate this.

Create a new project directory somewhere on your computer and execute the following from your Terminal (Mac and Linux) or Command Prompt (Windows) after navigating into it:

We’re including all the Angular 2 scripts and making use of the my-app custom selector. However, pay close attention to the following line:

<script src="js/sha.js"></script>

This is the external JavaScript library that we’re going to use. It is jsSHA, a hashing library that I’ve used in many of my other projects. Download the library from GitHub and drop it in your project’s src/js directory.

With our project foundation laid out, it is time to work with our final two files.

Starting with our project’s src/app/app.ts file, open it and include the following TypeScript code:

Conclusion

I typed out way more than I really needed to, but since it is a tricky subject to grasp I thought it would be necessary. I didn’t understand it at first from the other documentation online. You essentially need to declare some component of the external library before you can start using it.

If the library you plan to use includes a set of type definitions, you may want to read this followup article I wrote on the topic.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.