I’ve been working on a project that is about four years old. In recent days I moved towards working on new mini applications. In doing so I found myself needing to reference some of the code that exists in the old application. Instead of simply copy and pasting it into the new apps, I pursued figuring out how I could abstract these libraries/utilities. This would allow the code to be used outside that project and only needing to be maintained in one location.

Having knowledge of CommonJS and AMD module systems, I was stuck wondering how I could “use” modules in older systems that had no module loader, or as I call it “namespace” modules.

While using NPM packages I noticed that more and more front-end modules/libs/packages have appeared there. For example jQuery, knockout and so on. When loading these packages into a project I noticed that they supported the three scenarios mentioned above (CommonJS, AMD and no module loader). Looking into knockout’s code I saw the code that was solving this problem:

After researching, I found that the code above is pretty common, and in fact there was a name for it… UMD or Universal Module Definition. UMD helps in creating javascript modules that are support by all three module scenarios.

Utilizing build tools, you can turn regular code into UMD code.

Before:

After it’s been UMDified:

Now that you have pulled out this snippet of code from the legacy app, you need to reference it again. What I ended up doing was adding the reference into my package.json:

Adding the package into the build process:

And referencing the new module where the old namespace code was:

Now that the module had been successfully replaced in the legacy code, I could make use of the module in my new application that uses the CommonJS module pattern.

CommonJS seems to be the defacto method going forward. Build tools such as browserify and webpack make full use of the CommonJS pattern.

ES6 also outlines module loading with their “import” and “export” syntax, which follows the CommonJS pattern.

My drive to write this is to help other developers who may be stuck writing old code, for old websites, and help them move towards writing more modular, future proof javascript.