打字稿模块导入要未定义的案例类



我有两个文件

应用.js

///<reference path='mongodb.d.ts'/>
///<reference path='MyDatabase.ts'/>
module MyModule {
  import mongodb = module("mongodb");
  new mongodb.Server();
  var db = new MyDatabase(); // this will not work with first import line in Database.js, but work with second
}

我的数据库.js

///<reference path='mongodb.d.ts'/>
import mongodb = module("mongodb"); // adding this line here, will cause that app.js will not see MyDatabase class
module MyModule {
   import mongodb = module("mongodb"); // adding this line this will cause that classes in this module cant use mongodb
   export class MyData {
      _id: mongodb.Id; // second import line will cause this to be compilation error, with first line it works
   }
   export class MyDatabase {
       public test(): void {
          //with second line i can access mongodb here
       }
   }
}

所以问题是,我错过了什么?我应该如何导入 mongodb?

看起来您可能会将外部模块(export/import)与"内部"module块混淆?导入声明应仅存在于文件的顶层。

我认为

问题是 TS 引用路径是包含的,而不是导入的。只要不使用导入/导出,TS 编译器就会将所有内容放在"全局模块"中,使用引用路径将其拼接在一起。

一旦您开始在文件中使用导入/导出,该文件将被解释为其自己的模块,不再是全局模块的一部分。有关详细信息,请查看 TS 语言规范第 9.1 节。

所以,我怀疑 - 一旦你开始使用导入MyDataBase.ts - 你也需要将该文件作为外部模块导入(而不仅仅是引用它)。

最新更新