How can I export an ES6 class and instantiate it in another module?
Using Node.js version 7.7.2, I would like to define and export an ES6 class from a module like this:
// Foo.js
class Foo {
construct() {
this.bar = 'bar';
}
}
module.exports = Foo;
And then import the class into another module and instantiate said class like this:
// Bar.js
require('./foo');
var foo = new Foo();
var fooBar = foo.bar;
However, this syntax doesn't work. I am trying to do this, and if so what is the correct syntax for this?
Thank.
source to share
For this you need to use the normal node module syntax.
You have several errors in your example code. First, class
it shouldn't ()
. Also, the constructor of the class must be constructor
not construct
. Take a look below foo.js
for the correct syntax.
foo.js
class Foo {
constructor () {
this.foo = 'bar';
}
}
module.exports = Foo;
bar.js
const Foo = require('./foo');
const foo = new Foo();
console.log(foo.foo); // => bar
source to share