簡體   English   中英

class 的構造函數在模塊中需要后未定義

[英]constructor for class is undefined after require in module

我正在嘗試在節點中導入 class 以便我可以在我的主要 function 中創建它的實例,但是當我嘗試這樣做時,我收到錯誤Epicenter is not a constructor我在 ZA2F2ED4F8EBC2CBB614C20 之前嘗試使用導出並添加“A29DZ” :"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"
}

您應該將 class export如下:


// 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"用於nodejs包上的ES modules支持。 因此其他軟件包可以使用 package 處理最后一個 Node.js 版本的本地import

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM