How to split JS code in modular files/small chunks? (Step-by-step)

Henry
Javascript cheatsheet
4 min readJun 23, 2018

Let’s see the first files structure and how we are using it.

Note: This solution using webpack to compile all files and create one generic file for the application.

  1. We have one directory which include 4 files.
  2. main-index.js file will have reference of the modular files.

File a contain the function a() and it is calling the function b() and c() respectively.

At the end export function a() using module.exports so function a() will be available to other files.

Same way file b just having one function b() and that is printing the console.log()

File c is having one function c() and that is calling the another function b().

Let’s see the explanation of each statement and purpose.

Node is having 2 important and core modules for managing dependencies and we are going to use both.

In following screenshot first statement is a syntax and second statement is the actual usage. So here fileC.js is imported using require.

Now in fileC.js we are declaring the function c() and exporting it.

So what is module.exports? Whenever you want to export any object, function or classes at root level then module.exports is the trick. :)

Now webpack is going to compile all the files and will generate the one file. That file will have all the code from four files and it will look like this.

In your HTML , reference this file and you are good to go.

Step-by-step execution here.

  1. First mainfunction() will be executed from index file.

2. Then inside main-index file, it is going to read the require reference.

3. Then it will go to fileA and read the require reference for fileC.

4. Now it will come to fileC and read the require reference for fileB.

5. Now all the references are collected so it will come and execute the function call.

6. After step number 5, all the references are collected from respective file and ready to use. Like in step 5 callFunction variable is holding the function a(). So even though function a() is part for fileA it is ready to use number of times in this file through variable callFunction.

7. It will sequentially execute the functions and print the console. final output will look like this.

This is it! Really easy. :)

Let me know the feedback of this article. If you like and think this is helpful please share or applaud for this article. Also let me know if you want me to add more details to this article.

--

--