Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I export an ES6 class and construct an instance of it in another module?

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.

like image 200
Allen More Avatar asked Apr 25 '17 21:04

Allen More


People also ask

How do I create an instance of a class in ES6?

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.

What is the correct way of exporting a component in ES6?

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.

How do you use exported classes?

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.


1 Answers

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
like image 178
Mario Tacke Avatar answered Oct 23 '22 23:10

Mario Tacke