6
votes

How can I define the dependent modules in a AMD Module with TypeScript, including, for instance, jQuery and underscore. Using JavaScript I do, for example, like this:

define('moduleA',
    ['jquery', 'underscore'], function ($, _) {
    }
});

How can do this so that TypeScript compiler generates this code.

2
Remember, you can grab the definition of RequireJS and use it directly in your TypeScript code. stevefenton.co.uk/Content/Blog/Date/201302/Blog/…Fenton

2 Answers

3
votes

With the current implementation of the compiler (0.8) the way to achieve what you are seeking is the following.

test.ts:

import jquery = module("jquery");
import underscore = module("underscore");

export module A {
    console.log(jquery.$ + underscore._);
}

jquery.ts:

export var $ = null;

underscore.ts:

export var _ = null;

if you compile test.ts using the module switch:

tsc --module AMD test.ts

it will generate the following JS file for you:

define(["require", "exports", "jquery", "underscore"], function(require, exports, __jquery__, __underscore__) {
    var jquery = __jquery__;
    var underscore = __underscore__;
    (function (A) {
        console.log(jquery.$ + underscore._);
    })(exports.A || (exports.A = {}));
})

Note that if you put import statements inside the module it will note codegen correctly due to a bug. The team is currently working on a fix on that item but hopefully that shouldn't block you.

2
votes

This currently does not work correctly in typescript due to a bug in the compiler (see stackoverflow). What you would need to do is define a module moduleA that imports jquery and underscore, and then compile that with -module amd. Basically, you would need the following three files:

moduleA.ts

export module moduleA {
    import jquery = module("jquery");
    import underscore = module("underscore");
    console.log(jquery.jquery);
    console.log(underscore.underscore);
}

jquery.ts

export module jquery {
    var jquery = "jquery";
}

underscore.ts

export module underscore {
    var underscore = "underscore";
}

Compiling those three files with tsc -module amd yields the following code for moduleA.js:

define(["require", "exports"], function(require, exports) {
    (function (moduleA) {
        var jquery = __jquery__;

        var underscore = __underscore__;

        console.log(jquery.jquery);
        console.log(underscore.underscore);
    })(exports.moduleA || (exports.moduleA = {}));

})

Like I said above, due to a bug in the compiler, this code is actually incorrect and will complain about missing __jquery__ at runtime. However, once this bug is fixed the amd loader of node.js should be able to load the modules.