Reputation: 159
I want to create a Velbus (home automation) library to import in any project with Node.JS. However, there are plenty of function (sometime 6 or more) on each kind of Velbus modules, so I want to split my actual library into submodules (primitives_blind.js, primitives_relay.js, primitives_tempSensor.js, etc.) I can import them in my main library VelbusLib.js, but I don't know how to allow a user to only import my main module, but use function from submodules.
Example : primitives_blind.js
function blindUP(adr, part) { ... }
function blindDOWN(adr, part) { ... }
function blindStatus(adr, part) { ... }
module.exports = { blindUP, blindDOWN, blindStatus }
VelbusLib.js
const blind = require('./primitives_blind.js')
index.js (an App)
const velbusLib = require('./VelbusLib.js')
...
velbusLib.blindUP(0x40, 1) // blind.blindUP() not wanted, because user have to import all submodules
Of course, it's not possible to export function imported
module.exports = {
CheckSum,
Cut,
// blindUP or blind.blindUP aren't possible
A small schema is often better than a long discuss : Can someone explain to me the "State-of-the-art" about this? Thanks :)
Upvotes: 1
Views: 664
Reputation: 159
After much research, it appears that's not implicite to have many submodules (ModA, ModB, ModC) and import a module ModX in an app "APP" and use import ModA, ModB, ModC from it.
However, it's possible to export from ModX, some import from ModA or ModB or ModC :
In ModX.js:
import {actionA1, actionA2} from './ModA'
import ModB from './ModB'
import * from './ModC'
...
export { actionA2, ModB }
Then in app.js:
import ModX from './ModX'
...
let Foo = actionA2(something)
let Bar = ModB.actionB(somethingElse)
Thanks @bergi for his correction
Upvotes: 0
Reputation: 664297
I suspect you're looking for object literal spread syntax
const blind = require('./primitives_blind.js')
module.exports = {
CheckSum,
Cut,
...blind,
};
which essentially does the same as
const blind = require('./primitives_blind.js')
module.exports = {
CheckSum,
Cut,
blindUP: blind.blindUP,
blindDOWN: blind.blindDOWN,
blindStatus: blind.blindStatus,
};
However, since you were asking for the state of the art: use ES6 module syntax for the whole library, not CommonJS module.exports
! With that, it would be
export * from './primitives_blind.js';
Upvotes: 1