简体   繁体   中英

Requiring a module that requires itself

I have an index.js file that looks a little bit like this:

exports.services = {
    service1: require("./service1"),
    service2: require("./service2"),
}

service2 actually needs to make use of service1 , though. However inside of the service2.js file if I do:

var services = require("./").services

Then services will just be an empty object. This makes some sense since service2 is not completely required yet. Is there any way to give service2 access to service without requiring it explicitly?

Instead of doing it in an object literal all at once, you could do it by setting the properties separately. This way, when it encounters the circularity, it will already have loaded some of it:

exports.services = {};
exports.services.service1 = require("./service1");
exports.services.service2 = require("./service2");

Warning: untested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM