How to run a TypeScript app compiled into a single file with AMD modules?

Viewed 6482

I'm sure I'm missing something completely trivial here, but for the life of it I can't figure it out. Only recently have I started using AMD (RequireJS). My app will (would) run in browsers.


Setup

In TypeScript 1.8, it's possible to tsc an entire project composed of external modules into a single output file when using AMD.

For this reason, I finally decided to leave internal modules behind and make all of my VS2015 project .ts and .tsx files external modules, then compile them into a single file with the following compiler arguments:

--module AMD --outFile main.js

Output

The single output main.js file is created as expected, listed in it are all modules which are part of the project:

main.js

define("Project/MainModule", ["require", "exports" ...], function (require, exports ...) {
    "use strict";
    console.log("MainModule defined");
    // ...
});

...    

Usage (?)

Now, how do I get Project/MainModule to run from -- for example -- index.html (so that it logs "MainModule defined" into console)? I have RequireJS loaded to handle the AMD syntax, as well as the main.js file specified for immediate loading:

index.html

<script data-main="main" src="Require.js"></script>

This correctly loads main.js, which I ensured by including a call to console.log after the huge list of defines in that file (outside modules). Pardon me if this is a trivial question, I couldn't find anything concerning how to use a compiled application with this approach (maybe I didn't use the right keywords?).


Edit: I tried requiring the module by its name:

index.html

<script>
    window.onload = function () {
        require(["Project/MainModule"], function () {
            // this
        });
    }
</script>

... but it's no good, RequireJS can't find the module.

4 Answers

I've written SAMD for this exact use case: https://github.com/morris/samd

It provides a minimal AMD implementation, sufficient for TypeScript AMD bundles and dependencies included via regular script tags.

Related