Can I load multiple files with one require statement?

前端 未结 5 1345
佛祖请我去吃肉
佛祖请我去吃肉 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:37

    I have a snippet of code that requires more than one module, but it doesn't clump them together as your post suggests. However, that can be overcome with a trick that I found.

    function requireMany () {
        return Array.prototype.slice.call(arguments).map(function (value) {
            try {
                return require(value)
            }
            catch (event) {
                return console.log(event)
            }
        })
    }
    

    And you use it as such

    requireMany("fs", "socket.io", "path")
    

    Which will return

    [ fs {}, socketio {}, path {} ]
    

    If a module is not found, an error will be sent to the console. It won't break the programme. The error will be shown in the array as undefined. The array will not be shorter because one of the modules failed to load.

    Then you can bind those each of those array elements to a variable name, like so:

    var [fs, socketio, path] = requireMany("fs", "socket.io", "path")
    

    It essentially works like an object, but assigns the keys and their values to the global namespace. So, in your case, you could do:

    var [foo, bar] = requireMany("./foo.js", "./bar.js")
    foo() //return "hello from one"
    bar() //return "hello from two"
    

    And if you do want it to break the programme on error, just use this modified version, which is smaller

    function requireMany () {
        return Array.prototype.slice.call(arguments).map(require)
    }
    

提交回复
热议问题