Bower and Require.js Integration
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.
1 2 3 4 5 6 7 8 9 | { "name" : "RequireJS Starter" , "version" : "1.0.0" , "dependencies" : { "jquery" : "1.9" , "underscore" : null , "requirejs" : null } } |
1 2 3 4 5 6 7 8 9 | 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:
1 2 3 4 5 6 7 8 9 10 | 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)); }); |
Comments
Post a Comment