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

StackOverflow https://stackoverflow.com/questions/23688610

Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

If you have a file called jquery.d.ts in the same path, and that file is written with a top-level export (instead of a declare module "jquery" {), then you don't need the reference tag.

You could also pass all of your .d.ts files as explicit arguments to tsc

Otherwise, there's no way for the compiler to know where to find type information about the jQuery module.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top