Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

254
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

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

notice keyword EXPORT

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda