0

I am building an application composed of a set of modules that get loaded when the application bootstrap:

const MODULES = [] function registerModules(config) { return modules.map(module => (new module(config)).install()); } function bootstrap() { MODULES = registerModules({...}); } 

The above of-course will raise an error. What I want to do is to assign the MODULE constant only when the app start but then it should be fixed. Is this possible?

Initialisation of MODULES has to happen inside bootstrap because of the config variable that I have to pass to registerModules.

1 Answer 1

1

If indeed you want to:

  • Have an initialised, but empty MODULES array during the time that bootstrap() is not yet called, and
  • Make MODULES immutable once it has been populated, and
  • Keep the current function signature of registerModules unchanged;

Then you could do it as follows:

function bootstrap() { Object.freeze(Object.assign(MODULES, registerModules({...}))); // OR: // MODULES.push(...registerModules({...})); // Object.freeze(MODULES); } 

If you don't insist on the existence of MODULES before bootstrap() is called, and you are open to store that information inside an object, then you could proceed as follows:

const globals = {}; function bootstrap() { globals.MODULES = registerModules({...}); Object.freeze(globals.MODULES); } 

Once you are happy with globals, you can also freeze that object:

Object.freeze(globals); 
Sign up to request clarification or add additional context in comments.

6 Comments

To be complete, one could also freeze the individual modules, not just the MODULES variable... although the OP didn't mention if the individual modules should also be fixed.
thank you, it seems currently this the only available option, though it will only assure immutability but it still can be completely reassigned.
@adnanmuttaleb, can you explain what you mean with completely reassigned? Neither MODULES = , nor MODULES[0] = will work once bootstrap() has executed...
@trincot I mean MODULES =, because MODULES[0] = means object is mutable.
MODULES = will not even work in your original code, because of const? That is the reason why I suggested Object.assign/.push(...)...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.