×
☰ See All Chapters

TypeScript AMD Module Loader

In this tutorial you will learn How to run a TypeScript app compiled with AMD modules. To run the compiled javascript files you should include require.js file into your HTML page. To this require.js we should specify the main javascript source file to data-main attribute, that’s all. Rest all loading of remaining source files will be taken care by require.js dynamically. You can download require.js file from here https://requirejs.org/docs/download.htm   Let us see how this happens by following through an example.

IShape.ts

export interface IShape {

   draw();

}

Circle.ts

import shape = require("./IShape");

export class Circle implements shape.IShape {

   public draw() {

      console.log("Cirlce is drawn (external module)");

   }

}

Triangle.ts

import shape = require("./IShape");

export class Triangle implements shape.IShape {

   public draw() {

      console.log("Triangle is drawn (external module)");

   }

}

TestShape.ts

import shape = require("./IShape");

import circle = require("./Circle");

import triangle = require("./Triangle");  

 

function drawAllShapes(shapeToDraw: shape.IShape) {

   shapeToDraw.draw();

}

drawAllShapes(new circle.Circle());

drawAllShapes(new triangle.Triangle());

tsconfig.json

{

        "include": [

                "WebContent/ts/*"

        ],

        "compilerOptions": {

                "noEmitOnError": true,

                "outDir": "WebContent/js",

                "module": "amd"

        },

        "exclude": [

                "requireJS"

        ]

}

Project Directory Structure

typescript-amd-module-loader-0
 

Compile ts files

typescript-amd-module-loader-1
 
typescript-amd-module-loader-2
 

welcome.html

<!DOCTYPE html>

<html>

    <body>

            <script  data-main="../js/TestShape.js" type="text/javascript" src="../requireJS/require.js"></script>

    </body>

</html>

Output

typescript-amd-module-loader-3
 

All Chapters
Author