2012-12-12 97 views
8

有一种方法导入或注释打字稿模块,使得产生AMD-兼容模块?:自动将AMD代码包含在Typescript AMD模块中?

tsc --module AMD example.ts 

当我试图包括包括参考外部AMD模块将自动被包括作为依赖性* .d.ts文件和导出声明语句:

///<reference path='./lib/knockout-2.2.d.ts' /> 

export declare var $; 
export declare var _; 

export module example { 
    export class Example { 
     // whatever 
    } 
} 

但是生成的模块不包括这些:

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; 
}) 

真的想避免在这里创建“假”模块。

这似乎是一个很好的解决方案和使用是允许直接导入AMD模块:

var $ = import('jquery'); // This is a requirejs/AMD module, not a typescript file. 

,但我不知道这是怎么可行。

编辑:

而且我也试过这种方法这里所说:Import TypeScript module using only ambient definition for use in amd

import knockout = module("./lib/knockout-2.2.d.ts"); 
... 

但获得这些编译器错误:

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 
+0

你找到一个很好的解决方案? –

+0

不 - 在我的情况下,我开始意识到将我的Typescript应用程序连接到单个文件('tsc -out')会更容易,而不必担心AMD,因为不会懒惰加载任何内容。 – 7zark7

+1

我刚刚找到/// - 但是可以在我回家时先测试它。 –

回答

3

在最近的版本打字稿的做,这是正确的方式...

例(恰好是jQuery的)

第1步:从的NuGet(即jQuery的下载定义文件。打字稿)

步骤2:下面是代码(参考注释是没有必要在Visual Studio):

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

import $ = require('jquery'); 

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

将所得的JavaScript:

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

淘汰赛

一些人们在淘汰赛中遇到了麻烦......同样的技术也适用于淘汰赛...

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

import ko = require('knockout'); 

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

所得的JavaScript:

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

此:

declare module 'jquery' { export var n; }; 

import $ = module('jquery'); 

export module foo { 
    var n = $.n; 
} 

将导致正确define电话:

define(["require", "exports", 'jquery'], ... 

请注意,如果你没有在位置使用进口值($在这个例子中)(如类型位置不是只)中,编译器会优化这个依赖关系。

+0

谢谢瑞安,会给它一个镜头。虽然我知道JS模块空间与CommonJS,AMD等有点混乱,而不是TypeScript的错误 - 但在没有这些解决方法的情况下,在TS中轻松包含外部模块似乎很有价值。 – 7zark7

+2

不能让它为淘汰赛工作。当导入ko = module('knockout')时,ko不能用作ko.observable()之后 –

0

Ryan的回答工作,除了新的声明隐藏了三重注释“.d.ts”文件中引用的类型。

为了克服这个问题,你可能要尝试改变声明是这样的:

declare module 'knockout' { export = knockout; } 

我没有淘汰赛测试,但该解决方案应该与同样工作。