2012-12-12 95 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; } 

我沒有淘汰賽測試,但該解決方案應該與同樣工作。