[Node.js / CommonJS]
I'm creating a single GitHub repo for my tool which has a Core, Control, Server, and Client library. It's unlikely that all of them will be used at the same time.
I'd like my fellow coworkers to require
one entry point for all four libraries. So I made this questionable implementation: exporting the Core class with static properties pointing to the other classes.
Tool.js
class Core
{
static get Control(){return require("./control")};
static get Server(){return require("./server")};
static get Client(){return require("./client")};
constructor(opts)
{
}
}
module.exports = Core;
// module.exports = {Core, Control, Server, Client};
index.js
//Create core instance
const Tool = require("Tool");
const tool = new Tool();
//Create server instance
const ToolServer = require("Tool").Server;
//etc
const ToolClient = require("Tool").Client;
Is this a bad pattern? I'd RTFM in regards to importing classes from static properties, but I'm not sure where to find resources that dives deep into the inner workings of JavaScript/Node.js/CommonJS.
require()
learn to map"Tool"
toCore
? – candied_orange May 25 '18 at 9:47"Tool"
resolves to"Tool.js"
or something like that.Core
is the name of the class definition, not necessarily the filename. – Vic May 25 '18 at 9:53Core
class is defined inTool.js
, andrequire("Tool")
somehow knowsCore
is the only class to care about in there? – candied_orange May 25 '18 at 10:02{Core, Core2}
is shorthand for{Core: Core, Core2: Core2}
which means you would need to do something likerequire("Tool").Core2.Server
to get the Server class. – Vic May 25 '18 at 10:22Core
class tomodule.exports
, unlike the previous example which was assigning an object{Core: Core}
instead. I suggest you read up on ES6/ESNext and CommonJS if you want to learn more about this. – Vic May 25 '18 at 10:58