Thursday, 27 April 2017

Can't use loaded modules outside of a function

I have an issue where I'm trying to save space in my project, so I have created a function to try/catch any errors with required modules, but once loaded I can't seem to figure out how to use the loaded modules outside of the given function.

Most of my modules are used for json, though there are some functions used inside others, mainly for validation. Here is the code I'm trying to execute in main.js.

function requireModule(module) {
    try {
        require(module);
    }
    catch (e) {
        console.log("The module " + module + " could not be loaded.")
    }
}

var Foo = requireModule("foo");
var Bar = requireModule("bar.js");
var Baz = requireModule("./baz"); //Simple addition function

console.log(Baz(1,2));

When executing this code, I am met with the following error.

console.log(Baz(1,2));
        ^
TypeError: Baz is not a function

I've tried some troubleshooting, moving the function into the try/catch and also logging the module paths. This is the result

foo
The module foo could not be loaded.
bar.js
The module bar.js could not be loaded.
./baz
The module ./baz could not be loaded.

I expect the errors regarding loading the foo and bar modules, after all the module for baz hasn't loaded yet. However, once the baz module loads it still seems to fail.

Am I doing something stupid or am I just missing the point? Is there an easier way around what I'm trying to achieve that doesn't involve separate try/catch functions for each required module?

Kind regards



via Glazbee

No comments:

Post a Comment