[英]NodeJS module.exports submodule
Folks, Trying to include other .js files to be able to export from a module in the following manner.伙计们,尝试包含其他 .js 文件以便能够以下列方式从模块导出。 This will make the main module more readable.
这将使主模块更具可读性。 I am trying to include code from other functions.
我正在尝试包含来自其他函数的代码。
I suppose its not the correct way.我想这不是正确的方法。 Can someone guide me in the right direction?
有人可以指导我朝着正确的方向前进吗?
main module file:主模块文件:
module.exports = {
eval(fs.readFileSync('./extras/foo.js')+'');
fdsa: function (barf, callback) {
},
asdf: function (barf, callback) {
},
}
foo.js: foo.js:
foo: function (barf, callback) {
...
callback(err, result);
}
If you want main.js to basically duplicate and enhance everything foo has (which is silly, but that seems to be what you are asking), you can do this:如果您希望main.js基本上复制和增强 foo 的所有内容(这很愚蠢,但这似乎是您要的),您可以这样做:
main.js主文件
var foo = require('./extras/foo');
for (var prop in foo) {
exports[prop] = foo[prop];
}
exports.fdsa = function(...
exports.asdf = function(...
./extras/foo.js ./extras/foo.js
exports.foo = function(...
Side note if you put a file in somedir/index.js
, it can be required as just somedir
, which can also be useful.旁注如果你把一个文件放在
somedir/index.js
,它可能只是somedir
,这也很有用。
If you just want access to foo
by way of main and are OK with a sub-namespace, just do:如果您只想通过 main 访问
foo
并且可以使用子命名空间,请执行以下操作:
main.js主文件
exports.foo = require('./extras/foo');
Then your calling code can do:然后您的调用代码可以执行以下操作:
require('./main').foo.foo(blah, callback);
Also note if you want the entire foo
module to be a function, just do:另请注意,如果您希望整个
foo
模块成为一个函数,只需执行以下操作:
module.exports = function foo(barf, callback) {...
There is a much simple way to achieve this with es6 module pattern.使用 es6 模块模式有一种非常简单的方法可以实现这一点。 So in foo.js
所以在 foo.js 中
export function foo(barf, callback) {
...
callback(err, result);
}
And in main.js you will have something like,在 main.js 中,你会有类似的东西,
export * from './foo.js';
export function fdsa(barf, callback) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.