Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export ES6 class in Node 4.x Unexpected reserved word

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?

like image 328
Jake Wilson Avatar asked Oct 15 '15 18:10

Jake Wilson


Video Answer


2 Answers

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;
like image 100
morkro Avatar answered Oct 17 '22 21:10

morkro


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

like image 24
Anid Monsur Avatar answered Oct 17 '22 21:10

Anid Monsur