Splitting JavaScript into Separate Files/Modules

May 12, 2015

For some time I have been trying to find the best way of how to split my JavaScript code into modules and have one module per file. It sounds simple enough but it can start to require references between the files and get quite messy.

After looking at a number of techniques on the internet I have based this on what I think if the easiest to both implement and use:

var moduleName = (function () {

  var aPrivateVar = "I am private";
  var aPublicVar = "I am public";

  var aPrivateMethod = function () {
      // code here
  };

  var aPublicMethod = function () {
      // code here
  };

  // Public API. Only definitions here give public scope
  return {
    aPrivateVar: aPrivateVar,
    aPublicMethod: aPublicMethod
  };
})();

To use this technique:

  • Split your code into logical modules. Similar to creating Classes.
  • Anything public you must declare as in the bottom of the above example. You don’t necessarily need to use the same name as the function you have declared
  • Reference each file in your main HTML file (<script src=”…)
  • When making cross-module calls just use the format moduleName.aPublicMethod.

It actually works well and you don’t need to worry about the order of files. It’s like having all the declarations in one file but it is a much neater solution. Although JavaScript may lack true Classes, this is close and you can maintain public and private scope.