Automatically include AMD deps in Typescript AMD module?

requirejs, typescript

Solution

In the more recent versions of TypeScript the correct way to do this is...

Example (happens to be jQuery)

Step 1: Download the definition file from NuGet (i.e. jquery.typescript)

Step 2: Here is the code (the reference comment isn't necessary in Visual Studio):

/// <reference path="scripts/typings/jquery/jquery.d.ts" />

import $ = require('jquery');

export module foo {
    var elem = $('#myid');
}

The resulting JavaScript:

define(["require", "exports", 'jquery'], function(require, exports, $) {
    (function (foo) {
        var elem = $('#myid');
    })(exports.foo || (exports.foo = {}));
    var foo = exports.foo;
});

Knockout

Some people were having trouble with Knockout... The same technique works for Knockout...

/// <reference path="scripts/typings/knockout/knockout.d.ts" />

import ko = require('knockout');

export module foo {
    var obs = ko.observable('example');
}

The resulting JavaScript:

define(["require", "exports", 'knockout'], function(require, exports, ko) {
    (function (foo) {
        var n = ko.observable('example');
    })(exports.foo || (exports.foo = {}));
    var foo = exports.foo;
});

Problem

Is there a way to import or annotate Typescript modules such that external AMD modules will automatically be included as dependencies when generating an AMD-compatible module?: ``` tsc --module AMD example.ts ``` I've tried to include both including a reference *.d.ts file, and exporting declare statements: ``` ///<reference path='./lib/knockout-2.2.d.ts' /> export declare var $; export declare var _; export module example { export class Example { // whatever } } ``` However the generated module does not include these: ``` define(["require", "exports"], function(require, exports) { (function (example) { var Example = (function () { function Example() { } return Example; })(); example.Example = Example; })(exports.example || (exports.example = {})); var example = exports.example; }) ``` Would really like to avoid creating "fake" modules here. It seems like a nice solution and usage would be to allow importing AMD modules directly: ``` var $ = import('jquery'); // This is a requirejs/AMD module, not a typescript file. ``` but I don't know how feasible that is. Edit: And I've also tried this approach mentioned here: Import TypeScript module using only ambient definition for use in amd ``` import knockout = module("./lib/knockout-2.2.d.ts"); ... ``` but get these compiler errors: ``` example.ts(1,32): The name '"./lib/knockout-2.2.d.ts"' does not exist in the current scope example.ts(1,32): A module cannot be aliased to a non-module type ```

Original source

Related problems