9

I have the following in a Node scripts:

"use strict";

class Whatever {
    constructor() {
        console.log("I'm in the constructor!");
    }
}

export default Whatever;

I get Unexpected reserved word regarding export.

What am I missing here? How do you specify a class definition in an external file and include/require it?

1
  • 2
    I don't think ES6 modules are supported in Node by default, are you running this with the --harmony, --harmony_modules flag etc ?
    – adeneo
    Commented Oct 15, 2015 at 18:36

2 Answers 2

7

Node.js doesn't support ES6 modules by default. You would need to activate them with the --harmony or --harmony_modules flag. Default ist the CommonJS declaration (require/module.exports).

Modify your code to support the CommonJS syntax:

"use strict";

class Whatever {
    constructor() {
        console.log("I'm in the constructor!");
    }
}

module.exports = Whatever;
3
  • As I said in the question, I'm using Node 4. Thanks Commented Oct 15, 2015 at 18:43
  • Ah, sorry :) Skipped that part then. Will update my answer.
    – morkro
    Commented Oct 15, 2015 at 18:44
  • Thanks I saw it supported ES6 classes and just assumed that is the proper way to export classes. Didn't realize you could use the old CommonJS syntax for classes still. Thanks Commented Oct 15, 2015 at 22:18
2

ES6 modules aren't stable in Node yet, but you can use --harmony_modules to enable them. This obviously is not recommended in a production environment.

ES6 support in Node 4.x

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.