Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Include External JavaScript Libraries In An Angular TypeScript Project

TwitterFacebookRedditLinkedInHacker News

I’ve been a JavaScript developer for a while now, but with the release of Angular, 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 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 is in its first beta stage, but breaking changes shouldn’t be introduced (per the Angular 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:

mkdir src
mkdir src/app
mkdir src/js
touch src/tsconfig.json
touch src/index.html
touch app/app.ts
touch app/app.html
npm init -y

Of course you need the Node Package Manager (NPM) already installed.

With the project directories and files in place, run the following to get all the Angular dependencies:

npm install angular2@2.0.0-beta.0 systemjs typescript live-server --save

Remember, I’m using the first beta of Angular, but you can play around with versions.

Open your project’s package.json file and add the following two scripts:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "tsc": "tsc -p src -w",
    "start": "live-server --open=src"
},

This allows us to watch for file changes and run a live server for our application.

Now open your project’s src/tsconfig.json file and include the following:

{
    "compilerOptions": {
        "target": "ES5",
        "module": "commonjs",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
    }
}

These are TypeScript settings for compiling.

This brings us to our first HTML file. Open your project’s src/index.html and include the following code:

<html>
    <head>
        <title>Angular QuickStart</title>
        <script src="../node_modules/angular2/bundles/angular2-polyfills.js"></script>
        <script src="../node_modules/systemjs/dist/system.src.js"></script>
        <script src="../node_modules/rxjs/bundles/Rx.js"></script>
        <script src="../node_modules/angular2/bundles/angular2.dev.js"></script>
        <script src="js/sha.js"></script>
        <script>
            System.config({
                packages: {'app': {defaultExtension: 'js'}}
            });
            System.import('app/app');
        </script>
    </head>
    <body>
        <my-app>Loading...</my-app>
    </body>
</html>

We’re including all the Angular 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:

import { Component, View } from "angular2/core";
import { bootstrap } from "angular2/platform/browser";

declare var jsSHA: any;

@Component({
    selector: "my-app",
    templateUrl: "app/app.html",
    directives: []
})

class App {

    shaObj: any;
    hash: String;

    constructor() {
        this.shaObj = new jsSHA("SHA-512", "TEXT");
        this.shaObj.update("This is a test");
        this.hash = this.shaObj.getHash("HEX");
    }

}

bootstrap(App, []);

I’ve declared jsSHA since it is a class inside of the jsSHA library. Then in the constructor method I use the library exactly as it is described in the official documentation.

The final file is our project’s src/app/app.html file. Open it and add the following few lines of HTML:

<h1>SHA-512 Hash</h1>

<p>String: This is a test</p>
<p>HEX: {{hash}}</p>

The {{hash}} text is pulling data from our App class’s hash variable. It is the SHA-512 HEX that jsSHA creates.

To test out our project, open two Terminal windows. In the first window execute the following:

npm run tsc

In the second Terminal, execute the following:

npm run start

You should be able to access your project via http://127.0.0.1:8080/src/ in your web browser.

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.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

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