这是我想要实现的一个简单示例:
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)