I have a .js file which contains a class definition (with the class syntax, not the function one, in case it matters). Then i want to have a folder with multiple files, each of which will be a function that creates a different instance of said class, with different properties, and returns the instance. Of course, the single instance creating file cannot access class information unless each of these files has its own "require("class definition.js");" line. The point is, since i'm going to have hundreds of said instance creating files, will the repeated "require" kill my performance? I dont trust JavaScript, i'm basically scared it will parse and replace the class definition each time "require" appears. Does anyone know if that happens? If it does is there any workaround? Thanks.
Relevant code example:
class_definition.js
class myclass { constructor(a) { this.a = a; } } instantiate_0.js
require("class_definition.js"); module.exports = function() { return new myclass(0); } instantiate_1.js
require("class_definition.js"); module.exports = function() { return new myclass(1); } test.js
var arr = []; for(var i=0; i<2; i++) { arr[i] = require("instantiate_" + i)(); } What i'd like to have is indeed something like c++'s .h files, something working like the "#pragma once" directive for the class definition file.
requirewill see that you have already required it in your code, and should get the cached required version back (more in the node.js docs). After requiring, it will then be cached inrequire.cache