了解内部/外部模块并导入/要求Typescript 0.8.2

时间:2013-02-12 15:09:19

标签: typescript

有很多关于这个主题的StackOverflow问题,但要么与我正在尝试的不同,要么与以前版本的TypeScript相同。

我正在开发一个相当大的TypeScript项目,并且已经将一个给定的模块分解为多个文件,而不是每个类都有一个。

在0.8.0中,这很好用:

//* driver.ts *//
/// <reference path="express.d.ts"/>
/// <reference path="a.ts"/>
/// <reference path="b.ts"/>

//* a.ts *//
/// <reference path="driver.ts"/>
module m {
  import express = module("express");

  export class a {
    A: m.b;
    A2: express.ServerResponse;
  }
}

//* b.ts *//
/// <reference path="driver.ts"/>
module m {
  export class b {
      B: number;
  }
}

在0.8.1中,我必须使用 导出导入 技巧更改 a.ts

//* a.ts *//
/// <reference path="driver.ts"/>
module m {
  export import express = module("express");

  export class a {
    A: m.b;
    A2: express.ServerResponse;
  }
}

但是,在0.8.2中,导入不能再在模块声明中,因此 a.ts 已更改为:

//* a.ts *//
/// <reference path="driver.ts"/>
import express = module("express");
module m {

  export class a {
    A: m.b;
    A2: express.ServerResponse;
  }
}

现在出现错误,因为 a.ts b.ts 中看不到模块的扩展名。

我的理解:

  
      由于导入声明,
  • a.ts 已成为外部模块。
  •   
  • 删除 a.ts 中的导入,允许a和b以及我的模块合并在一起。
  •   
  • 将导入更改为require语句会丢失 express.d.ts
  • 中的类型定义   

我不明白:

  
      
  • 如果没有将所有模块文件合并在一起,我真的没办法解决这个问题吗?
  •   

如果在其他地方得到解答,我道歉 - 只需将我链接到那里 - 但其他类似问题似乎都没有明确回答。

1 个答案:

答案 0 :(得分:5)

这就是我对你的情况所做的。

您的模块......

您需要在模块后面命名文件,因此a.ts实际应该是m.ts,并且应该包含类似的内容......

import express = module('express');

export class a {
    A: b;
    A2: express.ServerResponse;
}

export class b {
    B: number;
}

您不应在此处使用reference语句。

当您在nodejs上运行代码时,您无法真正将代码分割为多个文件,因为文件本身就是您的模块 - 当您import m = module('m');它将查找m.js时。您可以做的是将文件整理到文件夹结构中。

import x = module('m/x'); // m/x.js
import y = module('m/y'); // m/y.js
相关问题