Access Module Variables/Functions from Addon Script

To keep my addon tidy, I’m breaking up logic into different modules. My question is, if a module sets a variable or has a function that I want the addon script to access, how do I enable that? So far this doesn’t seem to be working for me.

Here is a sample module:

var var1 =  'hello world';

function foo()
{
  return 'hello world';
}

Here is my addon script:

var moduleA = require("data/moduleA");
console.log( moduleA.var1);  //var 1 not found
console.log( moduleA.foo() ); //foo not found

How do I allow my addon script to access the data that is setup in the modules? Thanks.

The short answer is you don’t :slight_smile:

Modules have their own private scope. Calling require() on a module gives you access only to the exports object defined inside that module. The exports object is the return value of the require() function call. I don’t see an exports object in your module definition, but assuming var1 and foo aren’t properties of it then you don’t see them.

Note that although you don’t have access to objects other than the properties of exports, internal data and functions are still shared between all importing scopes. For example, your var1 is the same var1 in every single javascript scope (within the same application process) that imports the module. Not just having the same value as in your example, but actually the same piece of memory. So if a call to the module from one place caused var1 to get a different value, t would have the new value when called from somewhere else. This is efficient because all your different scopes only need one instantiation of each function and other objects, and convenient because you can now have a shared global state between different javascript scopes, but also dangerous because trying to remember aspects of an individual scope inside the module will cause subtle bugs and memory leaks.

OK, so that was the short answer :slight_smile: The long answer is you might be able to do this by writing your own customer module loader. I don’t recommend it, but maybe you can have some fun trying.

Thanks @Lithopsian. I wasn’t aware of the exports object. That’s good enough for me.