The UrBlog

John's Ramblings about Software Development

A Simple JavaScript Module Library

When developing JavaScript, I like to break my code into modules and define what modules the depend on. Require.JS is a great tool for this, but it also means bringing in module loading. I’m on a project using Grails that has a moderate amount of JavaScript. Grails provides a resource plugin that handles bundling of resources. I would still like to use the Require.JS style of defining modules and their dependencies while still loading scripts the normal way so Grails is happy.

I ended up creating define.js. This libary provides a simple ‘define’ and ‘require’ method. The ‘define’ uses the global object to hold the modules so they are also available in html handlers. Using the global object as the module list also allows us to treat third party libraries such as jQuery as dependencies.

The following example creates a module that depends on the domain.person module, jQuery and the window object. Since we are using the global to store modules, we can treat jQuery and window just like any other dependency we have defined.

Using the global object to hold modules also allows us to access them in html