我可以使用一个require语句加载多个文件吗? [英] Can I load multiple files with one require statement?

查看:337
本文介绍了我可以使用一个require语句加载多个文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这个问题有点愚蠢,但是是否可以使用一个require语句加载多个.js文件?像这样:

maybe this question is a little silly, but is it possible to load multiple .js files with one require statement? like this:

var mylib = require('./lib/mylibfiles');

并使用:

mylib.foo(); //return "hello from one"

mylib.bar(): //return "hello from two"

在文件夹mylibfiles中将有两个文件:

And in the folder mylibfiles will have two files:

One.js

exports.foo= function(){return "hello from one";}

Two.js

exports.bar= function(){return "hello from two";}

我当时正在考虑将package.json放在要加载所有文件的文件夹中,但我不知道如何.我在想的另一种方法是让index.js再次导出所有内容,但我将重复工作.

I was thinking to put a package.json in the folder that say to load all the files, but I don't know how. Other aproach that I was thinking is to have a index.js that exports everything again but I will be duplicating work.

谢谢!

P.D:我正在Windows 7计算机上使用Node.js v0.611

P.D: I'm working with nodejs v0.611 on a windows 7 machine

推荐答案

首先使用require不会重复任何内容.它会加载模块并对其进行缓存,因此再次调用require将从内存中获取它(因此您可以在不与源代码交互的情况下即时修改模块-有时这是理想的,例如当您要将数据库连接存储在模块内部).

First of all using require does not duplicate anything. It loads the module and it caches it, so calling require again will get it from memory (thus you can modify module at fly without interacting with its source code - this is sometimes desirable, for example when you want to store db connection inside module).

package.json不会加载任何内容,也不会与您的应用程序进行交互.它仅用于npm.

Also package.json does not load anything and does not interact with your app at all. It is only used for npm.

现在您不能一次需要多个模块.例如,如果One.jsTwo.js都定义了具有相同名称的函数,将会发生什么?还有更多问题.

Now you cannot require multiple modules at once. For example what will happen if both One.js and Two.js have defined function with the same name?? There are more problems.

但是您可以做的是写一个附加文件,例如具有以下内容的modules.js

But what you can do, is to write additional file, say modules.js with the following content

module.exports = {
   one : require('./one.js'),
   two : require('./two.js'),
   /* some other modules you want */
}

然后您可以简单地使用

var modules = require('./modules.js');
modules.one.foo();
modules.two.bar();

这篇关于我可以使用一个require语句加载多个文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆