0

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
4

2 回答 2

5

您当前正在导出具有以下属性的对象ShoppingCart

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

只需导出ShoppingCart

module.exports = ShoppingCart;

或者,在导入时,引用ShoppingCart对象的属性:

const { ShoppingCart } = require("./ShoppingCart")
于 2019-06-08T08:56:47.543 回答
0

您正在导出具有属性的对象ShoppingCart

任何一个:

  1. 将您的导出更改为module.exports = ShoppingCart;,

  2. 改变你requireconst { ShoppingCart } = require("./ShoppingCart");

如果您使用的是现代版本的 Node.js,则可以考虑使用 ESM(E CMA S脚本模块)代替(/ ):exportimport

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

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

它使用 JavaScript 的原生模块,而不是 Node.js 的 CommonJS 变体。在新的几年里,这将成为标准的做法。现在,要使用 ESM,您需要使用--experimental-modules标志和package.json包含type: "module". package.json type(或者,您可以使用文件扩展名来代替字段.mjs。)详情请点击此处

于 2019-06-08T08:57:25.347 回答