013 RequireJS

31 Aug 2012

Require.js is a JavaScript file and module loader. A modular approach can improve the maintainability and quality of our code. In this episode, we will see how we can convert a project containing many script tags to just a single script tag, with greater support for dependancies and modules.

Download video: mp4

Sample code: Github

Version: 2.0.6

##Tools used for Require.js:

  1. Sublime Text Editor
  2. Require.js and its API
  3. Chrome Developer Tools: Network Panel

##Steps to integrate Require.js into your project

###Setup the MAC OSX Apache Web Server

  1. Open the project file, index.html with web server and view space.localhost in the browser
  2. Move the project folder to MAC OSX Sites folder
  3. Start MAC OCX’s built-in Apache Web Server by opening System Preferences > Sharing > check Web Sharing
  4. Edit the hosts file located at /private/etc/hosts with the line space.localhost
  5. Ensure line Include /private/etc/apache2/extra/httpd-vhosts.conf is uncommented in the file /private/etc/apache2/httpd.conf
  6. Edit the vhosts file located at /private/etc/apache2/extra/httpd-vhosts.conf with the code [amend the file path accordingly]:
<VirtualHost *:80>
  ServerName space.localhost
  DocumentRoot "/Users/username/Sites/space-exploration"
  <Directory /Users/username/Sites/space-exploration>
    AllowOverride All
    Order allow,deny
    Allow from all

View space.localhost in the browser

###Steps to integrate require.js

  1. Download require.js file in the js folder
  2. Remove all inline script tags calling individual javascript files and instead use <script type="text/javascript" src="js/require.js" data-main="js/config"></script> in the head tag.
  3. Create config.js and main.js and edit them accordingly

##More Resources on Require.js

  1. What is AMD?
  2. Writing Modular JavaScript With AMD, CommonJS & ES Harmony by Addy Osmani
  3. How to structure your app using require.js
  4. Modular Javascript
  5. require.js 3 part series screencast by Cary Landholt
    1. basics part 1
    2. basics part 2
    3. optimizer
  6. Other example for your script loading needs

##Build Link of this Episode

jQuery Fundamentals by Jessica Murphey


Thanks to Sebastiaan and Thomas for RequireJS advice