malandro
malandro

Reputation: 107

My class created doesn't export an object

I need to create the class ShoppingCart in the file ShoppingCart.js and export it to a test file and i get the error that my class is not a constructor

I know the problem is not in import export because before creating the js file i got the error that it couldn't find the module. I also tried creating a new instance of the class inside the file and it worked

file ShoppingCart.js
class ShoppingCart{
    constructor(name){
        this.name=name
    }
}

module.exports = { ShoppingCart}

The code for my test file is

 const ShoppingCart = require("./ShoppingCart")
 new ShoppingCart()

when i run the test file i get

TypeError: ShoppingCart is not a constructor

Upvotes: 0

Views: 718

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075925

You're exporting an object with a ShoppingCart property.

Either:

  1. Change your export to module.exports = ShoppingCart;, or

  2. Change your require to const { ShoppingCart } = require("./ShoppingCart");

If you're using a modern version of Node.js, you might consider using ESM (ECMAScript Modules) instead (export/import):

export class ShoppingCart{
    constructor(name){
        this.name=name
    }
}

and

import { ShoppingCart } from "./ShoppingCart.js";
new ShoppingCart();

That uses JavaScript's native modules rather than Node.js's CommonJS variant. Over the new couple of years, this will become the standard way of doing it. For now, to use ESM you use the --experimental-modules flag and a package.json containing type: "module". (Or, instead of the package.json type field, you can use the file extension .mjs.) Details here.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371233

You are currently exporting an object with a property of ShoppingCart:

module.exports = { ShoppingCart }
//               ^^   object   ^^

Just export ShoppingCart:

module.exports = ShoppingCart;

Or, when importing, reference the ShoppingCart property of the object:

const { ShoppingCart } = require("./ShoppingCart")

Upvotes: 5

Related Questions