2013-09-01 172 views
21

我只是想把我的身邊打字稿頭,導入打字稿模塊

說我有一個模塊animals.ts這樣的:

export module Animals { 

    export interface Animal { 
     name(): void; 
    } 

    export class Elephant implements Animal { 

     constructor() { 

     } 

     public name() { 
      console.log("Elephant"); 
     } 
    } 

    export class Horse implements Animal { 

     constructor() { 

     } 

     public name() { 
      console.log("Horse"); 
     } 
    } 
} 

而且我想在另一個文件中animals_panel.ts使用此模塊:

import animals = require("animals") 

module AnimalPanel { 

    var animal = new animals.Animals.Elephant(); 
    animal.name(); 
} 
  1. 這似乎有點不可思議,我認爲我必須使用animals.Animals.Elephant(),我會預計Animals.Elephant()。我做錯了什麼或者這是正確的行爲?
  2. 是否有可能在AnimalPanel模塊中導入import animals = require("animals")模塊(我嘗試這樣做時出錯)?
+1

[進口文檔](https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Namespaces%20and%20Modules.md) –

回答

30

當您使用外部模塊時,每個文件都是一個模塊。因此在文件中聲明一個本地內部模塊,例如export module Animals {導致不必要的雙重間接。

我將編碼animals.ts爲:

export interface Animal { 
    name(): void; 
} 

export class Elephant implements Animal { 

    constructor() { 

    } 

    public name() { 
     console.log("Elephant"); 
    } 
} 

export class Horse implements Animal { 

    constructor() { 

    } 

    public name() { 
     console.log("Horse"); 
    } 
} 

,然後用它作爲:

import animals = require("animals") 

module AnimalPanel { 

    var animal = new animals.Elephant(); 
    animal.name(); 
} 

PS:http://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1

+0

我在角度看到它們導入了一個模塊(比方說' NgModule)'然後他們說'@NMModule({})'。這是什麼意思?我的意思是'@ NgModule'(非常感謝) – M98

3
:關於這個主題的內部/外部打字稿模塊的視頻

您可以使用兩種類型的語法export/import

  1. (AMD風格)Require語法,支持ES5:

    var animals = require("animals");

  2. 使用import風格,從ES6開始suppurts:

    import { Elephant, Horse } from "animals";

打字稿支持export =到模擬傳統的CommonJSAMD工作流程。所以這兩個變種將起作用,並且我建議使用2nd,因爲它更強大的機制。

有關詳細信息,請參見official the TypeScript Modules web page