class 的构造函数在模块中 require 之后未定义

constructor for class is undefined after require in module

我正在尝试在 Node.js 中导入一个 class,这样我就可以在我的主要函数中创建它的实例 但是当尝试这样做时我得到错误 Epicenter is not a constructor 我已经尝试在我的 class 之前使用 export 并尝试将“type”:“module”添加到我的 package.json 但似乎什么都做不到区别,我也试过使用 import 但这也没有解决它:(

我的节点版本是12.17.0,希望有人能出出主意,不胜感激

这是我的主要模块

const Epicenter = require("./EpicenterClass.js");


// makes a board where nodes are assigned randomly to slots 

const makeboard = (nodes, randomLimit) =>{
var map = [[]];
var nodeCount = 0;
map.length = Math.floor(Math.random(10)+randomLimit);

console.log('making board',map,nodeCount,map.length)
for (const xloc of map) {
    Math.floor(Math.random(10)+1) > xloc && nodeCount < nodes ? map[xloc] = new Epicenter(1,2,3,4) 
    :
     map[xloc] = '';
    nodeCount++

    for (const yloc of map[xloc]) {
    Math.floor(Math.random(10)+1) > yloc && nodeCount < nodes ? map[yloc] = new Epicenter(1,2,3,4) 
    :
     map[yloc] = '';
    nodeCount++
      }     
  }

console.log(`${nodes} nodes generated, map generated: ${map}`)
}

makeboard(10, 2)

这是我的震中 class

// adds an epicenter for an earthquake which can be placed on the board
   class Epicenter {
    constructor(lat, long, magnitude, width) {
      this.lat = lat;
      this.long = long;
      this.magnitude = magnitude;
      this.width = width;
    }

    shiftMagnitude(){
      this.magnitude = Math.floor(Math.random(10)+this.magnitude);
      console.log('Magnitude of epicenter has changed')
    }
  }

我的package.json

也供参考
{
  "name": "edge_testing_lab",
  "version": "1.0.0",
  "description": "testing lab",
  "main": "generateMap.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "person",
  "license": "ISC"
}

您应该 export 您的 class 如下所示:


// adds an epicenter for an earthquake which can be placed on the board
class Epicenter {
    constructor(lat, long, magnitude, width) {
      this.lat = lat;
      this.long = long;
      this.magnitude = magnitude;
      this.width = width;
    }

    shiftMagnitude(){
      this.magnitude = Math.floor(Math.random(10)+this.magnitude);
      console.log('Magnitude of epicenter has changed')
    }
  }
module.exports = Epicenter;

配置 "type": "module" 用于 ES modulesnodejs 软件包的支持。 因此其他包可以处理使用带有最后 Node.js 版本的本机 import 的包。