我有这个文件结构:
project
|
| -- src
| |
| |--util
| |
| |--StringUtils.ts
| |--Constants.ts
|
| -- test
|
| -- catalog
|
| -- issue
|
| -- myTest.ts
文件内容:
StringUtils.ts:
module Util {
export class StringUtils {
static format(formatString:String, ...replacements:string[]):String {
return formatString.replace(/{(\d+)}/g, function (match, number) {
return typeof replacements[number] != 'undefined'
? replacements[number]
: match;
})
}
}
}
myTest.ts:
import imported = require("../../../src/util/StringUtils");
exports.testSomething = function(test) {
var testOutput:String = imported.Util.StringUtils.format("{0}, this is a test", "Mofo");
test.ok(true, "this assertion should pass");
test.done();
};
使用nodeunit运行时,我得到:
TypeError:无法读取未定义
的属性'StringUtils'
如何正确引用该文件?
答案 0 :(得分:2)
您可以忘记模块并使用ES6的import语句。您的代码应该如下所示
StringUtils.ts:
export class StringUtils {
static format(formatString:String, ...replacements:string[]):String {
return formatString.replace(/{(\d+)}/g, function (match, number) {
return typeof replacements[number] != 'undefined'
? replacements[number]
: match;
})
}
}
myTest.ts:
import {StringUtils} from "../../../src/util/StringUtils";
exports.testSomething = function(test) {
var testOutput:String = StringUtils.format("{0}, this is a test", "Mofo");
test.ok(true, "this assertion should pass");
test.done();
};
修改
实际上,对模块和命名空间存在误解。在新版本的Typescript中,所谓的modules
现在是namespaces
。来自文档:
关于术语的说明:在TypeScript中注意这一点非常重要 1.5,命名法已经改变。 “内部模块”现在是“命名空间”。 “外部模块”现在只是“模块”,以便对齐 使用ECMAScript 2015的术语,(即模块X {是 相当于现在首选的命名空间X {)。
建议使用ES6的方法,其中每个文件本身都是一个模块,但是如果你仍然想使用命名空间来分隔文件中的代码,那么你需要在定义模块之前定义命名空间:
namespace Util {
export class StringUtils {
.....
然后将其导入到您想要使用的经典之处:
/// <reference path="path.to.file.ts"/>