有两种方法可以在 HTML 页面中加载内容。
Bundling
第一个是手动包含页面中的所有脚本文件。您可能会运行某种预发布步骤来合并和缩小您的代码 - 但您要对此负责,而不是将其留给代码来做。这通常称为捆绑。
在捆绑的情况下,您只在 TypeScript 代码中使用引用(而不是导入),如下所示:
/// <reference path="./libs/underscore.d.ts"/>
module test {
export class Ctrl {
constructor($scope:any) {
$scope.name = "Freewind";
_.each($scope.name, function(item) {});
}
}
}
模块加载
如果您想使用模块加载器(对于 Web 来说通常是 RequireJS),您可以使用 import 语句加载外部模块。通常在这种情况下你不需要参考......
import _ = module("./libs/underscore");
module test {
export class Ctrl {
constructor($scope:any) {
$scope.name = "Freewind";
_.each($scope.name, function(item) {});
}
}
}
RequireJS 与非模块
还有第三种情况,这种情况很常见。如果您打算导入不是外部模块的东西 http://www.stevefenton.co.uk/Content/Blog/Date/201302/Blog/Using-RequireJS-and-Jquery-In-TypeScript/(例如 jQuery,但下划线也可能适合这种模式),您最好使用对 RequireJS 的引用和手动调用。
RequireJS 将为您加载依赖项,因此您可以用它包装您的主程序(可能位于一个单独的文件中,例如app.ts
.
///<reference path="./libs/require.d.ts" />
///<reference path="./libs/underscore.d.ts" />
module test {
export class Ctrl {
constructor($scope:any) {
$scope.name = "Freewind";
_.each($scope.name, function(item) {});
}
}
}
require(['underscore'], function (_) {
var ctrl = new test.Crtl({});
});
您还可以使用require.config
指定应用程序中下划线的路径。
require.config({
paths: {
"underscore": "libs/underscore"
}
});