1

What is the commonly accepted pattern to force initialization of a global state in es6 projects before any other code is executed?

//main.js
import './moduleA.js'

//Set up some state e.g. database connection or loggers. 
logger.configure(...)

//moduleA.js

//access db or logger
logger.log("I will fail since I am not configured yet!");

export default = () =>{
  ....
}

If moduleA requires access to the logger or the db connection they will fail, since the code of callee is resolved before the caller. Using an own module in which the initialization takes place and importing it before moduleA in the main will not solve the problem as the import resolution order is non deterministic.

Kilian
  • 1,540
  • 16
  • 28
  • 1
    "*Using an own module in which the initialization takes place and importing it before moduleA in the main*" … is exactly the solution you're looking for. "*import resolution order is non deterministic*" - not sure where you got that from? – Bergi Nov 25 '20 at 10:03
  • Is `logger` a global variable? Where does it come from? Create and initialise it in a module that *moduleA.js* imports, and it will be absolutely deterministic even with asynchronous imports. – Bergi Nov 25 '20 at 10:04
  • @Bergi I got this from this [answer](https://stackoverflow.com/a/35552247/3244464) _In other words, the two imported modules could execute their console.log() calls in any order; they are asynchronous with respect to one another_ In my exact use case the logger is `import winston from "winston"` . While it will be imported from multiple modules until ´winston.configure()´ is called the instance can not be used. – Kilian Nov 25 '20 at 14:57
  • That topic is specifically about ES6 module loading in browsers. Node.js does resolve, load and execute modules sequentially, see the docs. This certainly won't change until top-level `await`. – Bergi Nov 25 '20 at 15:23
  • 1
    Regarding winston, don't import that default instance directly `from "winston"`. Instead, just import an instance from an auxiliary logging module - where you import winston, configure it, and then export it. That ensures all other modules will get a configured instance. – Bergi Nov 25 '20 at 15:25

0 Answers0