How to export a Node class?

Asked

Viewed 830 times

-1

insira o código aquiVersion of Node 10.5.3 I am trying to export a class, to use it in another file. I have seen several examples on the internet and none of them helped me.

Below is the class I want to export.


class Retangulo {
    constructor(altura, largura) {
      this.altura = altura; this.largura = largura;
    }

    get area() {
        return this.calculaArea()  
    }  

    calculaArea() {  
        return this.altura * this.largura;  
    }
} 

module.exports = Retangulo;

And the file where I’m trying to use the Rectangular class

const Retangulo =  require('./teste.js');
var a =  new Retangulo(10,10)
console.log(a.area);

You can fix this error using "module.Exports = new Rectangle();", but then it returns an already instantiated object, and I want direct instantiation in the teste1.js file. I’m using the consign to load my routes.

This code is in my server.js file

consign().include('models').into(app);

Someone can help me with that. In case it’s not very clear, and just ask that I clarify.

  • 2

    What version of Node.js are you using? Find out by running node --version in your terminal. Post also your complete code in text form, image.

  • 1

    I suggest you read carefully how to make a good question here in the community.

  • For log error, the problem is in the library consign. You need to post the full code so we can help you.

  • I am trying to tidy up the issue. I ask apologies for the lack of organization of the questions, and I appreciate the tips.

1 answer

1

Using ES6

export default Retangulo and then do import Retangulo from "./teste.js" see more examples

Using previous versions

class Retangulo {
        constructor(altura, largura){
                this.altura = altura
                this.largura = largura
        }
        // . . .
}

module.exports = Retangulo;
const Retangulo = require("./teste.js")

const a = new Retangulo(23,23)
// . . .
  • 2

    export default and import are not natively supported in JS, and will only work if you are using a transpiler, such as babel or typescript.

  • 1

    Correction to previous comment: Not natively supported in Node.js, although very soon this will no longer be the case. It’s important to keep in mind that Javascript and Node.js are different things.

  • updated the reply, thanks for the comments, had forgotten this detail

  • The error continues gave Unexpected token export, and when I use the normal module.Xports it complains that it cannot export without the new: Typeerror: Class constructor Rectangular cannot be Invoked without 'new'

  • @Samuelribeiro you are wearing some transpilator?

  • What would that be?

  • one that is widely used is Babel, it serves to transform your code compatible with previous versions of javascript that are not supported

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.