Digital Transformation

How-To: Create a JavaScript module for CommonJS, Ti.include, or the browser

A common question we get is around techniques for code re-use between projects that use different types of JavaScript evaluation mechanisms, like the CommonJS module spec, Ti.include, or just in the browser. I thought I’d share a quick technique for creating a JavaScript module that will work in all three of these environments. Here’s the template for a simple module, before we dive into the usage:

In a CommonJS environment, we’ll add our public interface to the exports object as usual. But in environments that don’t provide the export object and an automatic sandbox, we need to be conscious of polluting the global JavaScript object by adding lots of global properties and functions. We can achieve this using a self-calling function to encapsulate the logic of our module, and only expose a single variable to the global scope, which we called globalNamspace above. This variable will become the public interface to our module in a Ti.include-style usage or in a standard script tag in the browser. To use the module in a CommonJS environment, your usage would look like this:

Using Ti.include, it would look like:

And in the browser, it would look like:

I hope that helps you create JavaScript modules that can be re-used in any environment.