TypeScript AMD with RequireJS Tutorial

Update: New and better Boilerplate that uses ES6 Modules in TypeScript check it out.

In this TypeScript RequireJS tutorial I will show you how to setup AMD classes, setup your config file and how to use RequireJS plugins with TypeScript.

TypeScript AMD Classes

Below is how we setup a AMD class that we can use with RequireJS. The most important part is to have the export statement below the class itself and to equal the class you created.

// Base.ts file
class Base {

    constructor() {
    }

    public createChildren():void {

    }
}

export = Base;

Next we want to import that Base.ts AMD TypeScript class into another class. You can see below how we have an import statement that will bring in our Base class.

// TestApp.ts file
import Base = require("view/Base");

class TestApp extends Base {

    private _title:string = 'TypeScript AMD Boilerplate';

    constructor() {
        super();
    }

    public createChildren():void {

    }

}

export = TestApp;

Once you have your RequireJS config file setup to load jQuery then you can do the following in your classes. Later I will should my config file.

import $ = require("jquery");

RequireJS Plugins TypeScript

Seems like this is an undocumented TypeScript feature. Below is what you need to use RequireJS plugins like the text! plugin or in this example the Handlebars(hbs!) plugin:

/// <amd-dependency path="hbs!templates/topbar/TopNavigationTemplate" />
declare var require:(moduleId:string) => any;
var TopNavigationTemplate:Function = require('hbs!templates/topbar/TopNavigationTemplate');

If you need to add multiple plugins into the file you will need to put all the /// <amd-dependency path=”” /> above the require code like:

/// <amd-dependency path="hbs!templates/topbar/TopNavigationTemplate" />
/// <amd-dependency path="hbs!templates/login/LoginTemplate" />
declare var require:(moduleId:string) => any;
var TopNavigationTemplate:Function = require('hbs!templates/topbar/TopNavigationTemplate');
var LoginTemplate:Function = require('hbs!templates/login/LoginTemplate');

RequireJS Config & Bootstrap Classes

Here is my RequireJS config file(AppConfig.ts):

require.config({

    baseUrl: 'assets/scripts/',

    paths: {
        //main libraries
        jquery: '../vendor/jquery/jquery-1.9.1',

        //shortcut paths
        templates: '../templates',
        data: '../data',

        //require plugins
        text: '../vendor/require/text',
        tpl: '../vendor/require/tpl',
        json: '../vendor/require/json',
        hbs: '../vendor/require-handlebars-plugin/hbs'
    },

    shim: {
        jquery: {
            exports: '$'
        }
    }
});

And here is my main RequireJS file(AppBootstrap.ts) that kicks everything off:

/// <reference path="_declare/require.d.ts" />

///<reference path='AppConfig.ts'/>
///<reference path='TestApp.ts'/>

/**
 * Main entry point for RequireJS
 */
require(
    [
        'TestApp',
        'jquery'
    ],
    (TestApp, $) => {
        'use strict';

        $(document).ready(function () {
            var app = new TestApp();
            app.appendTo('body');
        });
    }
);

RequireJS TypeScript Example Files

Be sure to check out my TypeScript AMD(RequireJS) Example files to see how to setup an TypeScript application with RequireJS.

6 Responses to “TypeScript AMD with RequireJS Tutorial”

  1. Thanks a lot!! I tried various ways in order to get my typescript work well with requirejs, tsc and full code-completion in PhpStorm but it never worked out.

    With your workaround using the custom require method it now all works together very well :). I just need to add the /// to the libs and to set the right type for the var in the require-line.

    Example for including lodash:

    ///
    ///
    declare var require:(moduleId:string) => any;
    var _ : _.LoDashStatic = require(‘lodash’);

    Well its four lines of code for one library but all the other things i tried out either didn´t work in require, threw errors in tsc or the code-completion in phpstorm wouldn´t show up.

    • Sorry, it kicked the tags in the comment-lines. The example should be:

      /// (reference path=”../../lib.d/lodash.d.ts” /)
      /// (amd-dependency path=”lodash” /)
      declare var require:(moduleId:string) => any;
      var _ :_.LoDashStatic = require(‘lodash’);

      just replace the round brackets ( ) with the angle bracket-style.

  2. […] so I won’t go in depth too much. Here are some good articles that google came back with: TypeScript AMD with RequireJS Tutorial, TypeScript: Organizing your code with AMD modules and require.js, The Definitive TypeScript […]

  3. thanks for this. I retrofitted Typescript onto existing RequireJS install. Some learnings for other users who may be new to this like me:

    1) I didn’t need to convert my existing requirejs config to typescript which was handy as it was in a separate shared location
    2) I mistakenly used “import” to try and load the existing requirejs modules. found it should only be used on typescript modules, stick with your existing require()
    3) to get intellisense working my require line now looks like:

    require[(‘jquery’, ‘toastr’)], function($, toastr: Toastr) {….

    where Toastr is picking up the interface definition for that library from the declaration file.

    hope this is of use.

  4. Diwakar Singh Says:
    December 25, 2015 at 4:55 am

    I have an application with the same architecture as you showed here.
    The only thing that I am unable to achieve is how should I enable the intellisence in config file.

    I mean auto complete for the modules that I have loaded in main.js is not working.

    Please suggest how to enable auto-complete in main.js file.

    Thanks

Leave a Reply