Reputation: 103
I have non-AMD backbone, non-AMD underscore and non-AMD jquery in my project. I also have a lot of third party libraries that are not AMD compatible.
What is the best way of having them compile alongside AMD modules using r.js? Should I start wrapping all of them into AMD modules?
I ran r.js on a module I had which was using non-AMD libraries and underscore and backbone, it generated an output but in the output wherever there is a require("backbone")
call, it returns undefined which I'm suspecting is because backbone is not registered as an AMD module.
At the same time something very strange to me is that if I do not run r.js and just run the website regularly using require.js loading, the following lines returns correct values even though they are not AMD modules:
var _ = require("underscore")
var Backbone = require("backbone")
I have those paths configured as aliases in my require.config.
Upvotes: 0
Views: 259
Reputation:
Why do you think, that backbone, underscore or jquery are not AMD compatible? They do! Just a bit not out of box. You just need to add a bit more configuration to your main.js. For example like this:
require.config({
paths : {
jquery : 'jquery-2.0.3',
backbone: 'backbone',
underscore: 'underscore'
},
shim : {
underscore: {exports: '_'},
backbone: {deps: ['underscore'], exports: 'Backbone'}
}
});
require(['jquery', 'backbone'], function($, Backbone) {
console.log('Type of $: ' + typeof $);
console.log('Type of Backbone: ' + typeof Backbone);
});
There aren't very much libraries, which are fully not AMD compatible (i. e. can't be used via RequireJs). Every library, which exposes itself to global scope via some property may be used via RequireJs.
But if you would like to use CommonJs modules (which are exposed via module.exports
), then the way I see, you have 2 options:
Use this construction:
define(function (require) {
var $ = require('jquery');
})
Both options work nice with RequireJs optimizer, as I tested.
Still, I would prefer use shim option in your main.js file.
Upvotes: 2