admin管理员组

文章数量:1279085

If I reference a TypeScript declarations file (ex. jquery.d.ts) using the /// <reference path="..."/> syntax, it's up to me to make sure I load the corresponding library by some other means, i.e. just referencing the .d.ts file doesn't load the library.

Is there a way to make TypeScript generate a require() call for the library when I use it? If I wasn't using AMD/requirejs I could just call require manually, but I'd like to get this to work with AMD.

The advantage of this is that my dependencies wouldn't be defined in two places. Referencing the library from a .ts file would be enough to make sure it loads, rather than having to maintain the list of dependencies manually in my HTML.

Update: I opened a new question that clarifies my exact situation. I want to give credit for the answer to my original question since I didn't give all the necessary details.

If I reference a TypeScript declarations file (ex. jquery.d.ts) using the /// <reference path="..."/> syntax, it's up to me to make sure I load the corresponding library by some other means, i.e. just referencing the .d.ts file doesn't load the library.

Is there a way to make TypeScript generate a require() call for the library when I use it? If I wasn't using AMD/requirejs I could just call require manually, but I'd like to get this to work with AMD.

The advantage of this is that my dependencies wouldn't be defined in two places. Referencing the library from a .ts file would be enough to make sure it loads, rather than having to maintain the list of dependencies manually in my HTML.

Update: I opened a new question that clarifies my exact situation. I want to give credit for the answer to my original question since I didn't give all the necessary details.

Share Improve this question edited May 23, 2017 at 12:23 CommunityBot 11 silver badge asked Oct 19, 2012 at 23:08 dcstrawdcstraw 3,3113 gold badges31 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Yes, TypeScript supports "external" modules, which are basically first class AMD or CommonJS modules. For example:

MyLib.ts

export function foo() { return 'bar' }

MyProj.ts

import lib = module('./MyLib.ts')
lib.foo(); // returns bar

Compile this with "--module amd" and you'll get the proper module and require syntax generated for you.

I wrote something about that on my blog. You can also find an example on GitHub.

The solution is rather long to explained, but basically I use shims with Require.JS to define a module name representing the Javascript library I want to load. I then create a TypeScript file with the same name to make the TypeScript piler generates Javascript code that can use the JS library I want. Doesn't really makes sense like this, but please read the post and I think it will make more sense.

本文标签: javascriptUse importrequire in TypeScript to get interface declarationsStack Overflow