Can I load multiple files with one require statement?

前端 未结 5 1346
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 13:31

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/mylib         


        
5条回答
  •  旧巷少年郎
    2020-12-13 14:18

    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).

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

    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.

    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 */
    }
    

    and then you can simply use

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

提交回复
热议问题