TypeScript and RequireJs

TypeScript and RequireJs work well together. Writing small modular code with Single Responsibilities (SOLID principles) is a good practice in any language and JavaScript is not an exception.

AMD-Dependency Path

Use amd-dependency path to include files you don’t need to use in code, but need to be loaded in order to run

///

Import

Use import (translates to define([‘jquery’]) for adding in dependencies. Casing matters and must match the casing of the file name. We name all of our TypeScript files starting with lower case.

A file that is included in the html source or at startup can be used for shortcuts to paths. Without this you’d have to do import $ = require(“Common/lib/jquery”) everywhere.

require.config({ paths: { “jquery”: “Common/lib/jquery” …} });

import $ = require(“jquery”); import myDataAccess = require(“dataAccess/myDataAccess”); “use strict;” // must go after import - see https://geekswithblogs.net/Aligned/archive/2015/01/30/order-matters-with-amd-dependency-typescript-and-use-strict.aspx class ILikeClassesInTypeScript {

}

export = ILikeClassesInTypeScript;

This article explains in more detail.

You can optimize the code (minifiy and combine) using a grunt task, since you don’t want the browser to have to retrieve the many modular files you’ll be creating. We’ve been using Grunt, but there are many Gulp plugins as well.

This article is part of the GWB Archives. Original Author: Aligned

New on Geeks with Blogs