I am new to JS design patterns and have not used much of require or import. I have a single module which contains multiple functions and private variables, which is packaged into a module. Currently everything is in one file but splitting it into multiple files would be good practice and provide better clarity. The simplified view of the module's pattern looks something like this:
let Module = () => {
//some private variables
let private1,
private2;
//some public functions
function addDatatoPrivate1 (data) {
private1 = processData(data);
}
function addDatatoPrivate2 (data) {
private2 = processData(data);
}
//private function processData
function processData(data) {
return data.trim();
}
return {
addDatatoPrivate1: addDatatoPrivate1,
addDatatoPrivate2: addDatatoPrivate2,
}
}
I would like to split up the functions into multiple files i.e. separate file for addDatatoPrivate1, addDatatoPrivate2 and processData. In addition I would like to have the variables private1 and private2 be available for other methods in the Module privately. How do I go about splitting the code into multiple files and then how to use import to get the different components of the module to package into one.
The eventual aim is to have something which a user can load into their own project and use something like d3js or jQuery. For example, with the code as above anyone can simply assign the module to a variable and use it like so:
let moduleInstance = Module();
moduleInstance.addDatatoPrivate1(' some data here ');
moduleInstance.addDatatoPrivate2(' some data here2 ');
You could use
ES6 modules.Steps:
ES6export.Now the user of the module can import the module like below.
Using
ES6object destructuringOR using wild card (*)
If you want to create separate module for each then you could do something like below.
module1.js
module2.js
module3.js
And then you can include these module and some other file.
or you could export all of you method in one file so other can import it and use.
index.js