如何在TypeScript中使用模块加载

时间:2015-04-24 20:56:19

标签: typescript

在TypeScript中,我有一个这样的代码:

莱文施泰因/ LevensteinAlgorithm.ts

export module levenstein {
    export class LevensteinAlgorithm
    {
        getDistance(left: string, right: string): number {
        // Some code for the alogorithm...
        }
    }
}

要对它进行单元测试,我已经在另一条路径中编写了一个测试:

测试/ levensteinAlgorithmTests.ts

/// <reference path="../scripts/typings/qunit/qunit.d.ts" />
/// <reference path="../levenstein/levensteinalgorithm.ts" />

QUnit.module("levensteinalgorithm.ts tests");

import levenstein = require("levenstein/LevensteinAlgorithm");

test("Simple update cost is equal to 1", ()=> {
// Arrange
var leven = new levenstein.LevensteinAlgorithm();

//... 

不幸的是,它有一个构建错误:

Property LevensteinAlgorithm doesn't exist on type: ....

我使用 QUnit Chutzpah 来运行测试。

我的模块加载有什么问题?

1 个答案:

答案 0 :(得分:2)

由于您将static String getResourceFileName(String maybePath) { Path path = Paths.get(maybePath); if (path.getNameCount() > 0) { return path.getFileName().toString(); } else { throw new IllegalArgumentException("Can't derive filename given " + maybePath); } } @Test public void testSoq() throws Exception { String fileName0 = getResourceFileName("file"); InputStream is0 = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName0); String fileName1 = getResourceFileName("src/test/resources/file"); InputStream is1 = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName1); String string0 = new BufferedReader(new InputStreamReader(is0)).readLine(); String string1 = new BufferedReader(new InputStreamReader(is1)).readLine(); assertEquals(string0, string1); // OK } 包裹在外部模块的内部模块LevensteinAlgorithm中,因此在将该对象导入为levenstein后引用该对象的方式为levenstein

此处的最佳解决方法是从levenstein.levenstein.LevensteinAlgorithm中删除export module Levenstein {并直接将该类导出外部模块。

另请参阅此处的“Needless Namepsacing”标题:https://typescript.codeplex.com/wikipage?title=Modules%20in%20TypeScript