In Typescript, what's the best way to load a config across multiple modules? Should you do this in every module that needs the config:

`import config from ''./config.js"`

OR should you import the config once and pass the config as a variable to any functions that need it? e.g.

```
import config from ''./config.js"
startServiceA(config);
startServiceB(config);
...
```

4
Share
Share on Mastodon
Share on Twitter
Share on Facebook
Share on Linkedin
playest

@paul I would, as much as possible, pass it as a parameter. That is much more flexible, extensible, and less "static"/global. I think that apply to other languages as well, not #typescript only. But that is just, you know, my opinion man.

0
1y
François Best

@paul Passing it as a parameter makes the modules much easier to test under different configurations, so I'd go for that.

I'd also type the config arguments as `Pick<ConfigType, 'whatever' | 'keys' | 'are' | 'needed'`>`, to limit the amount of boilerplate/mock needed in tests.

1
1y
Rockfish1292

@paul harder/ more work to use vs more flexible and easier to test.

Could even abstract it slightly more and have a factory function. Best of the two at the expense of more complexity.

0
1y
AirTwee

@paul I agree wirh @playest This way the module is bot dependent on a file very possible outside its scope.

0
1y
Replies