user3765109 user3765109 - 6 months ago 9
Javascript Question

File structure: Cascade accessing sub-modules or sub-files by using index.js file

modules/
|
|--- index.js
|
|--- module1.js
|
└--- module2/
|
|--- index.js
|
|--- component1.js
|
└--- component2.js


Using the structure above, I can access
module1.js
by using the following code;

var modules = require('./modules') // or import modules from './modules'
console.log(modules.module1)


However I cannot access to
component1
by the following code;

var modules = require('./modules') // or import modules from './modules'
console.log(modules.module2.component1)


When trying the code, the system throws
Cannot read property 'component1' of undefined
error. So, module2\index.js is not installed.

Is there any chance to access
component1
and
component2
by using
modules
definition?

Answer

Edit

I guess ES7 await method overcome this issue with a using like the following;

var modules = await require('./modules')
console.log(modules.module2.component1)

Original answer

The problem is that; Javascript codes work asynchronous.

At the first level is not a problem when defining to a variable. But at the second level needs some time to get and load the module from the depth.

Waiting to load the modules and then defining the components is nonsense in particularly when working on another Javascript platform like React-Native or one else platform which has been built on Javascript language.