如何在typescript中将类+子类拆分为两个文件?
// MongoModel.js
class MongoModel {
...
}
export = MongoModel;
然后在另一个文件中:
import MongoModel = require("./MongoModel");
但这是个错误
File ....MongoModel.ts is not a module
我是否需要使用一些模块语法将它们捆绑在一起,比如java包?
最佳答案
用于导出和导入模块的版本在编译器配置中以es5
为目标时工作。
当以es6
为目标时,您有以下导出/导入模块的方法:
// in MongoClass.ts
export class MongoClass {
// ... code here
}
// and in other file
import {MongoClass} from '/path/to/MongoClass';
或者您可以使用
default export
;// in MongoClass.ts
export default class MongoClass { ... }
export const somethingElse = 5;
// and import in some other file
// note that MongoClass can be renamed when is exported as default exported member
import BaseMongo from '/path/to/MongoClass';
// this cannot be renamed when importing
import {somethingElse} from '/path/to/MongoClass';