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.
Creating Objects To create an instance of the class, use the new keyword followed by the class name. Following is the syntax for the same. Where, The new keyword is responsible for instantiation.
ES6 provides two ways to export a module from a file: named export and default export. With named exports, one can have multiple named exports per file. Then import the specific exports they want surrounded in braces. The name of imported module has to be the same as the name of the exported module.
Use named exports to export a class in JavaScript, e.g. export class Employee {} . The exported class can be imported by using a named import as import {Employee} from './another-file. js' . You can use as many named exports as necessary in a file.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With