25

What is the right way to use a class defined in one file and extend it another, in node.js?

Currently I have:

'use strict'

class BasePageHandler {

    constructor(app, settings, context) {

    }
}

return module.exports;

In the 'child' class file I have:

'use strict'

var BasePageHandler = require ('./../BasePageHandler.js');

class FrontpagePageHandler extends BasePageHandler {
    constructor(app, settings, context) {
         super(app, settings, context);
         this.settings = settings;
         this.context = context;
    }
}

This fails with the following error:

TypeError: Class extends value #<Object> is not a function or null

Note, if I have the BasePageHandler in the same file then it works, so it is really when the class is in another file I have an issue.

Currently using node 4.4.0.

1

2 Answers 2

39

You need to correctly export your class inBasePageHandler.js file:

module.exports = BasePageHandler;
Sign up to request clarification or add additional context in comments.

5 Comments

Indeed. I missed the obvious :)
I'm pretty sure you can also just put it on 1 line: module.exports = class BasePageHandler { that way if you rename the class, it's 1 less place to change it later.
Event after doing this, I'm still having the same issue? I'm using the harmony_destructuring flag!
I had an issue similar where I was trying to return the class by making module.exports into a function. It worked but not as expected. By simply defining module.exports to be the class, everything worked as expected.
I did it too, but it does not work for me, any other solution please @madox2
17

The accepted answer is technically fine, but really if you're using ES6 then you should go all in and use ES6 export/import.

/*jshint esversion: 6 */

class BasePageHandler {
    constructor(app, settings, context) {
    }
}

export default BasePageHandler;

and then:

/*jshint esversion: 6 */

import BasePageHandler from './../BasePageHandler.js';

class FrontpagePageHandler extends BasePageHandler {
    constructor(app, settings, context) {
         super(app, settings, context);
         this.settings = settings;
         this.context = context;
    }
}

2 Comments

BTW, there's no need 'use strict' in ES6 - it's enforced by default.
When I do this I get "SyntaxError: Cannot use import statement outside a module" And I cannot for the life of my figure out why. What am I missing?

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.