【发布时间】:2019-07-11 00:55:05
【问题描述】:
我正在使用 nodejs 和 typescript 开发一个新的服务器(REST API)。在项目中有一个 API 文件夹,其中包含类文件。这些类继承自 API 基类。 App 类具有 initApi 方法,该方法从 API 文件夹on fly加载所有类。带有 API 类的文件也被编译成 *.js。由于它们继承自基类 Api,因此它们具有静态方法“isApi”。
但是,当我尝试使用 API 类要求编译文件 (*.ts -> *.js) 时,整个类定义上下文都会丢失,包括父类。
// Base API class
export default class Api {
public static isApi(): boolean {
return true;
}
}
// Test-API class inherited from API
// Which must be loaded inside App class as a compiled file (*.ts -> *.js)
import Api from "../Api";
export default class TestApi extends Api {
// Just for testing.
public async process() {
return;
}
}
// App class
class App {
...
private initApi() {
const apiRoot = path.join(__dirname, "api");
const walker = walk.walk(apiRoot);
walker.on("file", (root, fileStats, next) => {
// Reg is for JS (generated) files!!!
if (/^[^_].*\.js$/.test(fileStats.name)) {
const apiPath = root.substr(apiRoot.length + 1).replace(/\//g, ".");
const apiName = (apiPath ? apiPath + "." : "") + fileStats.name.substr(0, fileStats.name.length - 3);
const module_ = require(path.join(root, fileStats.name));
// Problem here: module_.isApi and module_.isApi() is undefined.
if (module_.isApi && module_.isApi()) {
this._api[apiName] = module_;
}
next();
}
}
...
}
module_.isApi 和 module_.isApi() 未定义。
【问题讨论】:
-
当你使用
require()导入带有默认导出的ES6模块时,做require(...).default
标签: javascript node.js typescript