Search code examples
javascriptjquerytypescriptamd

Avoid duplicate reference / import of external javascript library in Typescript when using AMD modules


Lets say I am using --module AMD to get AMD module support with Typescript and use requirejs. Now, using the jquery.ts.d from DefinetelyTyped I came up with the following minimal example:

/// <reference path="../../typings/jquery/jquery.d.ts" />
import $ = require("jquery");

export class Greeter
{
    sayHello() {
       $('#mydiv').text('hello world');
    }
}

One can clearly see that I have to reference jQuerytwo times: One time via the ///<reference ... /> statement and one time via the import jquery = require("jquery") statement.

Now, if I omit the ///<reference ... /> part, the typescript compiler tsc will complain about the unknown $variable. On the other hand, if I leave out the import statement, compilation will work but at runtime jQuerywill not be included (as it is not in the list of required components in the compiled sourcecode).

So the only way I see is to always include both statements, which feels wrong to me as I am repeating myself. I this the "expected way"(TM) or am I just missing something here?


Solution

  • I recommend adding a vendor.d.ts file that consolidates all your external definitions like :

    /// <reference path="./jquery/jquery.d.ts" />
    /// <reference path="./other/other.d.ts" />
    

    And then you only reference vendor.d.ts :

    /// <reference path="../../typings/vendor.d.ts" />
    import $ = require("jquery");
    

    BTW, if you are using tsd https://github.com/DefinitelyTyped/tsd it creates a tsd.d.ts file for you that plays the role of vendor.d.ts