Require.js 2.0

by Andy Appleton

At some point over the last few weeks Require.js 2.0 was released. It’s a really nice update which addresses a couple of pain points which I have experienced whilst using it.

Non AMD Shim

My favourite new feature is the built in shim for loading non-AMD compatible libraries. Loading non-AMD JavaScript in 1.x either required altering the code to include a define call or using the order plugin to manually configure the load order for different plugins.

Neither option was particularly nice so in 2.0 we get the option to shim files in requirejs.config(), for example:

requirejs.config({
  shim: {
    'backbone': {
      // Define dependencies
      deps: ['underscore', 'jquery'],
      // Set a value for the file to export
      exports: 'Backbone'
    },
    'backbone.validation': {
      deps: ['backbone'],
      exports: 'Backbone.Validation'
    }
  }
});

This makes it much easier to update non AMD libraries without worrying about breaking a wrapper. There are a few caveats to using this, but on the whole it’s a big improvement.

Fallback paths

2.0 has introduced errbacks - callbacks for error states. This allows us to account for modules which don’t load. A nice use for this is to specify a fallback path for the module - e.g. if we’re using a CDN version of a file.

Again this can be set in requirejs.config():

requirejs.config({
  paths: {
    jquery: [
      '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min',
      'lib/jquery'
    ]
  }
});

Require will attempt to load the module from each path specified in the array until it is succesful.

Lazy evaluation

In 1.x any built file (a bundle of a number of modules produced by the optimizer) would all be evaluated on load. This has changed in 2.0 and now code is only evaluated as it is called. This is a nice performance win as it defers a lot of browser work until it is needed.

These are my favourite new features, but there’s plenty more so check it out.