In the past we've talked about Bower package manager and God knows, I have been obsessively repeating myself about using Require.js and it's integration with object oriented programming. So how do they integrate with each other? In this article we'll cover the integration of both and see how they get along together.
Bower Initiation
Let's start by defining, which packages we want to use in our project by filling the bower.json. You can create one yourself or run bower init command for interactive creation.
{ "name": "RequireJS Starter", "version": "1.0.0", "dependencies": { "jquery": "1.9", "underscore": null, "requirejs": null } }So we'll be needing jQuery, Underscore and of course Require.js. Putting null as a version number will download the latest version. Now run bower install to download all the packages into bower_components folder. You can change the location along with other thing using .bowerrc configuration file. After everything is in place, we'll configure our dependencies in our entry point JavaScript file and use the libraries once retrieved:
require.config({ paths: { "jquery": "bower_components/jquery/jquery", "underscore": "bower_components/underscore/underscore" } }); require(['jquery', 'underscore'], function($, _) { $('body').text(_.range(10)); });
Automagical wire-up
This is how it works according to the writter of bower-requirejs plugin. It looks at the libraries installed by Bower and creates a JavaScript file with require.config call with all the paths in place. Just run the following line in your bash console:
./node_modules/.bin/bower-requirejs -c destination/config.jsIt has some interesting flags you can use, all of them well described in the documentation.
CDN Integration
But my mother told me local libraries are bad. She was right! We should always try to use CDN for common libraries, since chances are it had been already downloaded to user's computer and cached version would be used instead of downloading fresh version from our server. Let's edit our code and add cdnjs urls as a first priority. I prefer them over others because they offer the biggest variety of libraries and it's always good practice to work with a single provider. We'll leave our versions as a fallback if something bad happens to the CDN:
require.config({ paths: { "jquery": ["http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min", "bower_components/jquery/jquery"], "underscore": ["http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min", "bower_components/underscore/underscore"] }, waitSeconds: 10 }); require(['jquery', 'underscore'], function($, _) { $('body').text(_.range(10)); });Notice the waitSeconds parameter we've added configuring how much time to wait for the CDN's versions. Hope things started to clear bit by bit. What to use and how to use it. I'll continue to write articles on this topic including Grunt integration.