我正在尝试在客户端使用 typescript 和 angularjs。
我发现如果我使用外部模块,生成的js不会在浏览器中运行。
controllers.ts
/// <reference path="./libs/underscore.d.ts"/>
import _ = module("underscore");
module test {
export class Ctrl {
constructor($scope:any) {
$scope.name = "Freewind";
_.each($scope.name, function(item) {});
}
}
}
生成的js将是:
var _ = require("underscore")
var test;
(function (test) {
var Ctrl = (function () {
function Ctrl($scope) {
$scope.name = "Freewind";
_.each($scope.name, function (item) {
});
}
return Ctrl;
})();
test.Ctrl = Ctrl;
})(test || (test = {}));
无法正常运行。但是,如果我删除 module("underscore")
部分,就可以了。
由于我在HTML中添加了underscore.js,我想应该是require()
方法出了问题。如何解决?
最佳答案
有两种方法可以在 HTML 页面中加载内容。
捆绑
第一个是在您的页面中手动包含所有脚本文件。您可能会运行某种预发布步骤来合并和缩小您的代码——但您要为此负责,而不是将其留给代码去做。这通常称为捆绑。
在捆绑的情况下,您只在 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 与非模块
还有第三种情况,这很常见。如果你打算import something that isn't an External Module (例如 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"
}
});
关于require - 如果我使用 `module("somelib")` in typescript, it can' t 在浏览器中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14538099/