2012-12-16 49 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的帮助或者我看不到的东西? –