简体   繁体   English

Node.js:如何透明地要求和导出子模块

[英]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.我想在一个名为module的存储库中收集很多依赖项,所以我只需要对其他存储库有一个依赖项。 Is that possible:那可能吗:

index.js in module repository to gather submodules module存储库中的 index.js 以收集子模块

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 index.js 在another module/library中,我需要所有子模块,所以我需要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.我希望尽可能透明的是module存储库。 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.这个例子创建了一个fruit模块,它同时导出了apple模块和banana模块。

apple.js苹果.js

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

module.exports = { eatApple };

banana.js香蕉.js

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

module.exports = { eatBanana };

fruit.js水果.js

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

app.js应用程序.js

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

app.js (alternate) app.js(替代)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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