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

Crw*_*wth 8 typescript

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

我正在研究一个相当大的TypeScript项目,并且在一个给定的模块中分解了多个文件,而不是每个类都有一个.

在0.8.0,这工作正常:

//* driver.ts *//
/// <reference path="express.d.ts"/>
/// <reference path="a.ts"/>
/// <reference path="b.ts"/>
Run Code Online (Sandbox Code Playgroud)

.

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

  export class a {
    A: m.b;
    A2: express.ServerResponse;
  }
}
Run Code Online (Sandbox Code Playgroud)

.

//* b.ts *//
/// <reference path="driver.ts"/>
module m {
  export class b {
      B: number;
  }
}
Run Code Online (Sandbox Code Playgroud)

在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;
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,在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;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在给出了一个错误,因为a.ts没有看到模块的扩展b.ts.

我的理解:

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

我不明白的是:

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

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

Fen*_*ton 5

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

你的模块......

你需要在你的模块之后命名你的文件,因此a.ts,实际应该m.ts并且应该包含类似的东西......

import express = module('express');

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

export class b {
    B: number;
}
Run Code Online (Sandbox Code Playgroud)

你不应该reference在这里使用陈述.

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

import x = module('m/x'); // m/x.js
import y = module('m/y'); // m/y.js
Run Code Online (Sandbox Code Playgroud)

  • @Cwth我感觉到你的痛苦.TypeScript应该促进"应用程序规模"的开发,但是它阻止我们组织我们的项目,以便我们可以在接近应用程序规模的任何地方时对它们进行导航. (4认同)