小编Seq*_*oya的帖子

在节点js中将多个文件导出为单个模块

这是我想要实现的一个简单示例:

foo.js:

module.exports.one = function(params) { */ stuff */ }
Run Code Online (Sandbox Code Playgroud)

bar.js:

module.exports.two = function(params) { */ stuff */ }
Run Code Online (Sandbox Code Playgroud)

stuff.js:

const foo = require('Path/foo');
const bar = require('Path/bar');
Run Code Online (Sandbox Code Playgroud)

我想要做 :

otherFile.js:

stuff = require('Path/stuff');

stuff.one(params);
stuff.two(params);
Run Code Online (Sandbox Code Playgroud)

我不想做[在stuff.js]

module.exports = {
one : foo.one,
two: bar.two
}
Run Code Online (Sandbox Code Playgroud)

我带来的解决方案是:

const files = ['path/foo', 'path/bar']

module.exports =   files
    .map(f => require(f))
    .map(f => Object.keys(f).map(e => ({ [e]: f[e] })))
    .reduce((a, b) => a.concat(b), [])
    .reduce((a, b) => Object.assign(a, b), {})
Run Code Online (Sandbox Code Playgroud)

或者更丑/更短:

module.exports = …
Run Code Online (Sandbox Code Playgroud)

javascript node.js

8
推荐指数
1
解决办法
3020
查看次数

标签 统计

javascript ×1

node.js ×1