Last Updated: February 25, 2016
· iwootten

Use CommonJS Module Definitions with RequireJS

Your client side apps can quickly become unwieldy, but writing definitions that resemble:

], function ($, _, Backbone, SomeModel, SomeView) {


can be cumbersome and error prone. In the above example, if I add a new requirement and new argument and I don't notice that jquery.tmpl isn't defined as a parameter, I'm going to get a failure in my app. It's also annoying to copy and paste to other definitions, due to the module and parameter being on different lines.

I much prefer using the CommonJS format, where the code will be as below:

define(function (require, exports, module) {
  var $         = require('jquery'),
    _           = require('underscore'),
    Backbone    = require('backbone'),
    TimerModel  = require('models/SomeModel'),
    TimerView   = require('views/SomeView');


This way, we can easily add required modules with or without parameters. It's also extremely simple to copy the definition in part or it's entirety.