导入 TypeScript 模块

23

我只是在努力理解 TypeScript,

假设我有一个名为 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
导入的文档 - Ondra Žižka
2个回答

33
当你使用外部模块时,每个文件都是一个模块。因此,在文件内声明本地内部模块,例如 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();
}

附:有关TypeScript内部/外部模块的视频:http://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1


2
我看到在Angular中,他们导入了一个模块(假设是NgModule),然后他们说@NgModule({})。这是什么意思?我的意思是 @NgModule。(非常感谢) - Mohammad Kermani

2

您可以使用两种类型的语法export/import

  1. (AMD风格) Require 语法,在ES5中支持:

    var animals = require("animals");

  2. 使用从ES6开始支持的import语法:

    import { Elephant, Horse } from "animals";

TypeScript支持export =来模拟传统的CommonJSAMD工作流程。因此,两种变体都可以使用,我建议使用第二种,因为它更强大。

有关详细信息,请访问TypeScript模块官方网页


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接