1

I’m develop a new server (REST API) with use nodejs and typescript. In the project there is an API folder in which files with classes. These classes are inherited from the API base class. The App class has the initApi method, which loads all the classes on fly from the API folder. Files with API classes are also compiled into *.js. Since they are inherited from the base class Api, they have a static method "isApi".

However, when I try to require compiled files (*.ts -> *.js) with API classes, the entire class definition context is lost, including the parent class.

// 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 and module_.isApi() is undefined.

1
  • 1
    When you import ES6 module with default export using require(), do require(...).default Commented Jul 6, 2019 at 21:20

1 Answer 1

2

In the line where you require, try require().default

const module_ = require(path.join(root, fileStats.name));

to:

const module_ = require(path.join(root, fileStats.name)).default;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.