2016-07-01 60 views
1

我有這個文件的結構:打字稿正確的多個文件使用

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: Cannot read property 'StringUtils' of undefined

如何正確地引用該文件?

+0

嘗試從」 ../進口在ES6風格'進口{} StringUtils的.. /../src/util/String Utils「;''''''''''''''''''''''''''''可能需要從你的StringUtils.ts中刪除'module Util',只留下類StringUtils – iberbeu

+0

好吧,工作正常(刪除模塊)。發佈它作爲答案 –

+0

檢查我的答案更新 – iberbeu

回答

2

您可以忘記模塊並使用ES6的導入語句。然後,您的代碼應該是這樣的

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。從文檔:

A note about terminology: It’s important to note that in TypeScript 1.5, the nomenclature has changed. 「Internal modules」 are now 「namespaces」. 「External modules」 are now simply 「modules」, as to align with ECMAScript 2015’s terminology, (namely that module X { is equivalent to the now-preferred namespace X {).

建議使用ES6的方法,即每個文件都是一個模塊本身,但如果你仍然想使用命名空間中的文件分開你的代碼,那麼你需要確定你的命名空間您之前定義的模塊:

namespace Util { 
    export class StringUtils { 
    ..... 

,然後導入它,無論你想與經典的使用:

/// <reference path="path.to.file.ts"/>