Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

// Foo.js
export class Foo() {
    construct() {
        this.foo = 'bar';
    }
}

notice keyword EXPORT

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!