[英]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.