javascript - Proper way to chain require -
i new node , npm bearing me here.
i want package/modularize series of classes(in separate files) inherit base class , classes should visible end user/programmer. in other words want preserve previous requires have master object end user can require everything. require('event') requires item user/programmer.
"use strict"; const item = require('./item'); module.exports = class event extends item { constructor() { super(); this.typename = 'event'; this.json = '{}'; } static bind(service, eventid) { return new event(); } }
and
"use strict"; module.exports = class item { constructor() { this.typename = 'item'; this.json = '{}'; } static bind(service, itemid) { return new item(); } }
thanks help!
if want export multiple things a module, export parent object , each of things want export property on object. not "chaining" there isn't such thing exporting multiple top level items module.
module.exports = { event, item }; class item { constructor() { this.typename = 'item'; this.json = '{}'; } static bind(service, itemid) { return new item(); } } class event extends item { constructor() { super(); this.typename = 'event'; this.json = '{}'; } static bind(service, eventid) { return new event(); } }
then, using module do:
const m = require('mymodule'); let item1 = new m.item(); let event1 = new m.event();
or, can assign them top level variables within module:
const {item, event} = require('mymodule'); let item1 = new item(); let event1 = new event();
if have multiple classes each in own file , want able load them 1 require()
statement, can create master file require()
on each of individual files , combines them 1 exported object. then, when want import of them, can require in master file.
node.js modules designed such require()
in need in module , in each module wants use something. enhances reusability or shareability of modules because each module independently imports things needs. don't have global state has imported somewhere before of other modules work. instead, each module self-describing. makes more obvious people working on module depends on because there's require()
statement depends upon. may seem bit of typing people coming different environments might import once global namespace (and more typing), there reasons done way , honestly, doesn't take long used , can enjoy of benefits doing way.
Comments
Post a Comment