2012-12-16 51 views
9

我在寫一個使用TypeScript,Backbone和Mustache的Web應用程序。我想使用Requirejs進行依賴加載。從requirejs映射調用文本插件

我還在使用打開AMD編譯選項的TypeScript的Web Essentials visual studio插件。對於那些不熟悉這個的人來說,如果你導入外部模塊,它會把你的類型腳本文件包裝在AMD模塊中。 例如:

在類型腳本中,我將以下模塊導入到類型定義文件中。

export import Backbone = module("Backbone"); 
import mainTemplate = module("MainTemplate"); 

的輸出是一樣的東西:

define(["require", "exports", "Backbone", "MainTemplate"], function(require, exports, __Backbone__, __mainTemplate__) { 
//...code goes here ... 
}); 

爲模板,我宣佈一個類型定義文件中的以下內容:

declare module "MainTemplate" { } 

爲了支持requirejs插件,您需要聲明您的模塊爲:

declare module "text!MainTemplate.html" { } 

我想保持模塊名稱不含插件和文件擴展名。這將使我在未來有一定的靈活性。

我在require中有以下映射。

require.config({ 
    map: { 
     "MyModule": { 
      "MainTemplate": "text!MainTemplate.html" 
     } 
    } 
} 

這成功地調用了文本插件,但是該插件加載了錯誤的url。通過篩選文本插件的源代碼,我發現下面的代碼是罪魁禍首。

load: function (name, req, onLoad, config) { 
    ... 
    url = req.toUrl(nonStripName), 
    //returns "scripts/**text!**MainTemplate.html**.html**" 
    ... 
} 

如果我命名模塊,「MainTemplate.html」它工作正常,但我想繼續擴展出來的模塊名稱。

我用一個簡單的正則表達式替換修改了文本插件去掉插件引用和重複的擴展。

有沒有更好的方法來處理這個問題?

回答

11

跑進類似的問題。終於解決了。請參閱TypeScript: compiling removes unreferenced imports

/// <amd-dependency path="text!templates/application.htm" /> 

var applicationTemplate = require('text!templates/application.htm'); 
+0

這是一個體面的解決方法,希望他們將在未來支持此模塊語法。 – thomaux

0

我們爲我們的TypeScript應用程序使用Backbone和require.js。
我們不使用

import backbone = module("Backbone") 

語法,而是使用

/// <reference path="../../modules/Backbone.d.ts" /> 

引用,然後引導程序。
這樣,'text!htmlfile.html'語法與require.js完美配合。

我已經把一個博客上使用帶有打字稿和AMD require.js: http://blorkfish.wordpress.com/2012/10/23/typescript-organizing-your-code-with-amd-modules-and-require-js/

8

對於打字稿1.0這對我的作品。 首先,我創建了一個.d.ts文件,其中存儲了每個文本模板的所有模塊聲明。

//workaround for typescript's lack of support for requirejs text template notation 
//remember that a reference to the import variable has to be found in the class, otherwise typescript ignores the import 
declare module "text!views/details/details.html" { 
    var text: string; 
    export = text; 
} 
declare module "text!views/layout/layout.html" { 
    var text: string; 
    export = text; 
} 
declare module "text!views/home/home.html" { 
    var text: string; 
    export = text; 
} 

然後引用文本模板我將這些行添加到類/模塊的頂部。

/// <reference path="../texttemplate.d.ts"/> 
import detailsTemplate = require('text!views/details/details.html'); 

由於.d.ts文件是全局拾取的,因此實際上不需要參考線。但我將其添加爲解決方法的提醒。它也可以很容易地按Ctrl +點擊去d.ts.文件。

+0

爲什麼這比Sean Smith提供的答案更好?它只是讓我看起來更像打字。這樣做是否有語義優勢?比如Visual Studio IntelliSense的幫助或者我看不到的東西? –