R.E.M. Web Development

Making a JavaScript File AMD Compliant For Use With RequireJS

So I had to use a library that adds some features to Google Maps, it's called MarkerClusterer. I copied the file into my vendor directory and then realized it is not AMD compliant. My first thought was to put the define() wrapper around the code in the file, to make it compliant. And that actually worked, but I soon realized there is a better way. In the main.js file you can use a 'shim' and 'exports', like so:

 

require.config({
baseUrl: 'js',
paths: {
'jquery': '../vendor/jquery/jquery',
'underscore': '../vendor/underscore-amd/underscore',
'backbone': '../vendor/backbone-amd/backbone',
'async':'../vendor/requirejs-plugins/src/async',
'markerclusterer': '../vendor/markerclusterer/index'
},

shim:{
'markerclusterer':{
exports: "MarkerClusterer"
}
}

});

require(["router"],

function(Router) {
return new Router();
}

);

 

Then you can us it like any other dependency when you create a module:

 

define([
'jquery',
'underscore',
'backbone',
'markerclusterer',
'async!http://maps.google.com/maps/api/js?sensor=false'
],function($, _, Backbone, MarkerClusterer){

var Map = Backbone.View.extend({

//code goes here

});

return Map

});