I'm trying to import a class in node so I can make instances of it in my main function
but when trying to do so I get the error Epicenter is not a constructor
I have tried using export before my class and tried adding "type":"module" to my package.json but nothing seems to make a difference, I've tried using import as well but this doesn't resolve it either :(
my node version is 12.17.0, hoping someone will have some ideas, any insight is appreciated
here is my main module
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)
and here is my epicenter 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')
}
}
for reference also here is my 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"
}
CodePudding user response:
You should export
your class as bellow:
// 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;
the config "type": "module"
is for ES modules
support on nodejs
packages.
so other packages could handle using the package with native import
of last Node.js versions.