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

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.