0

Can I export class definition in JavaScript? For example,

in file "HelloWorld.js":

'use strict';

class HelloWorld {
  constructor(msg = 'Hello World~') {
    this.message = msg;
  }

  sayHi() {
    console.log(this.message);
  }
}

module.exports = HelloWorld;


Then in "index.js"

'use strict';
var HelloWorld = require('HelloWorld');

var myObj = new HelloWorld;
myObj.sayHi();


if I do "node index.js", then I got the error below:

  constructor(msg = 'Hello World~') {
                  ^

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/data/users/soltiho/fbsource/fbcode/video_templates/test_env/index.js:3:18)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)

my node is v5.5.0

Solti
  • 633
  • 2
  • 6
  • 17
  • 3
    try removing the `{ }` around `HelloWorld` (why do you think these are necessary?) – miraculixx Feb 03 '16 at 19:46
  • removing { } changes the error to: ** constructor(msg = 'Hello World~') { ^ SyntaxError: Unexpected token =** the { } was added because the file may contain more things laster, so just added.. no meaning for now. – Solti Feb 03 '16 at 19:54
  • What version of node are you using? You should probably be running this through babel or something as well. – thgaskell Feb 03 '16 at 19:57
  • just update the question to remove destructing part. – Solti Feb 03 '16 at 20:03
  • The error seems purely relating to the default parameter. if removing that default value and do "if (msg) { ... } else { ... }" instead, the flow works as expected. – Solti Feb 03 '16 at 20:09
  • 1
    Yep, default params are also not supported yet. – Felix Kling Feb 04 '16 at 07:02

1 Answers1

0

Node doesn't support destructuring (yet), and using destructuring would be wrong anyways. There is nothing special about importing/exporting a class. Import it like any other module:

var myValue = require('myVModule');
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143