Have searched for this, but looks like I'm using the wrong terms. Mostly find things about C++, C#, node, PHP classes etc.
Say one have two modules A and B and a script main.
AexportsfarmBexportsprintand usesA.farmmainimportsAandB
But B depends on the same state of A.farm as main.
The way I have done this now is:
mainimportsAmainimportsBBhas ainitializefunction where it get a reference toA.farmfrommain.
Example:
A
let animal = 'donkey';
export const farm = {
get_animal: () => animal,
set_animal: a => animal = a
};
B
let farm, color;
export const initialize = env => {
farm = env.farm;
color = env.COLOR;
};
export const print = () => {
console.log(
'The', farm.get_animal(),
'is going to be painted', color, '.'
);
};
main
import {farm} from 'A';
import {print, initialize as initialize_b} from 'B';
const COLOR = 'red';
initialize_b({farm, COLOR});
farm.set_animal('cat');
print();
The cat is going to be painted red.
Is it the way to do it?
Question is if this is the way to do it? In the real project there is about 5 dependencies in B from main and 3 exports from B to main.
The code of B was initially part of main but as it can be categorized under one theme I found it better to have in a separate module + it keeps main cleaner.
It feels a bit wonky.
Earlier, in no-module-code, I have typically had a PROJECT = {} object that I include first then attach shared functions and other things trough that.
I could have a import-export module, something like:
import_export
import {farm} from 'A';
import {print, initialize as initialize_b} from 'B';
const COLOR = 'red';
initialize_b({farm, COLOR});
export {farm, print, COLOR};
Then import the exports in main. But not sure if that would be any cleaner. The import_export could end up with a lot of exports and main lot of imports.