Using Node.js version 7.7.2, I'd 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 construct an instance of said class like this:
// Bar.js
require('./foo');
var foo = new Foo();
var fooBar = foo.bar;
However, this syntax does not work. Is what I am trying to do possible, and if so, what is the correct syntax to achieve this?
Thanks.
You have to use regular node module syntax for this.
You have a few mistakes in your sample code. First, the class
should not be followed by ()
. Also, a class constructor should be constructor
not construct
. Look at the below foo.js
for proper 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
// Foo.js
export class Foo() {
construct() {
this.foo = 'bar';
}
}
notice keyword EXPORT
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.