How to use any JavaScript library with RequireJS 2.1

I’ve been using Require JS for a while, having cut my teeth on 0.27.0, and gotten quite familiar with the order plugin that was a part of life when using non require-js libraries.

RequireJS 2.1 provides a different tool for including third party libraries, providing a “shim” object that forms a part of the requirejs config.

With the shim it is easy to add dependencies on non-require js pieces of code. Take a look a the documentation on the shim config(http://requirejs.org/docs/api.html#config-shim) for some details or see some examples below:

Using Twitter Typeahead with Require.js

http://twitter.github.io/typeahead.js/

shim: {
“typeahead”: ["jquery"]
}

Typeahead depends on jquery being loaded first. Because the API is done via jquery, we don’t need to worry about exporting anything.

Using Twitter Hogan with Require.js

http://twitter.github.io/hogan.js/
shim: {
“hogan”: {exports: “Hogan”},
}

hogan doesn’t depend on anything being loaded before it. It exposes itself on the global namespace as Hogan.

Using Twitter Bootstrap with Require.js

http://twitter.github.io/bootstrap/javascript.html

shim: {
“bootstrap”: ["jquery"],
}

Twitter bootstrap depends on jquery being loaded first. Because the API is done via jquery, we don’t need to worry about exporting anything.

URI with Require.js

http://medialize.github.com/URI.js/

shim: {
“URI”: ["jquery"],
}

pushing in a jquery dependency to uri. It has magic in it to detect if amd is being used, and will define itself as an amd module.

SerializeJSON jQuery plugin with Require.js

https://github.com/marioizquierdo/jquery.serializeJSON

shim: {
“jquery.serializeJSON”: ["jquery"],
}

serializeJSON depends on jquery being loaded first. Because the API is done via jquery, we don’t need to worry about exporting anything.

D3 with Require.js

http://d3js.org/

shim: {
“d3″: {exports:”d3″},
}

D3 doesn’t have any dependencies and exports itself with the d3 global object.

Rickshaw with Require.js

http://code.shutterstock.com/rickshaw/

shim: {
“d3″: {exports:”d3″},
“rickshaw”: { exports: “Rickshaw”, deps: ['d3']}
}

rickshaw depends on d3, and exposes itself with the Rickshaw global namespace.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>