简体   繁体   中英

Node.js: How to transparently require and export submodules

I want to gather a lot of dependencies in one repository called, lets say module , so I only need to have one dependency for other repositories. Is that possible:

index.js in module repository to gather submodules

const submoduleA = require('submoduleA')
const submoduleB = require('submoduleB')

exports.submoduleA = submoduleA
exports.submoduleB = submoduleB

index.js in another module/library where I need all submodules, so I require module

const { submoduleA, submoduleB } = require('module')

Is that possible in any way? I know it's not a huge benefit, but would be nice to explain how all the submodules came about to be available.

What I want to be as transparent as possible is the module repository. Only requiring it to get all the other dependencies, but not getting in the way of normal syntax for those dependencies.

This example creates a fruit module that exports both the apple module and the banana module.

apple.js

function eatApple() {
  return 'Yummy apple!';
}

module.exports = { eatApple };

banana.js

function eatBanana() {
  return 'Yummy banana!';
}

module.exports = { eatBanana };

fruit.js

module.exports = {
  apple: require('./apple'),
  banana: require('./banana')
};

app.js

const fruit = require('./fruit');
console.log(fruit.apple.eatApple(), fruit.banana.eatBanana());

app.js (alternate)

const { apple, banana } = require('./fruit');
console.log(apple.eatApple(), banana.eatBanana());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM