【问题标题】:Importing TypeScript modules导入 TypeScript 模块
【发布时间】:2013-09-01 07:22:05
【问题描述】:

我只是想了解一下 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")(尝试执行此操作时出现错误)?

【问题讨论】:

标签: typescript


【解决方案1】:

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

【讨论】:

  • 我在 Angular 中看到他们导入了一个模块(比如说NgModule),然后他们说@NgModule({})。这是什么意思?我的意思是@NgModule(非常感谢)
【解决方案2】:

你可以使用两种语法export/import:

  1. (AMD 风格)Require ES5 支持的语法:

    var animals = require("animals");

  2. 使用从 ES6 开始支持的 import 样式:

    import { Elephant, Horse } from "animals";

TypeScript 支持 export = 来模拟传统的 CommonJS 和 AMD 工作流程。所以这两种变体都可以工作,我建议使用 2nd,因为它的机制更强大。

更多详情请见official the TypeScript Modules web page。

【讨论】:

    猜你喜欢
    • 2015-05-08
    • 2015-08-13
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2016-09-06
    • 2021-11-04
    • 2012-10-09
    相关资源
    最近更新 更多