Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

253
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

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

notice keyword EXPORT

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda