013 RequireJS
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:
- Sublime Text Editor
- Require.js and its API
- Chrome Developer Tools: Network Panel
##Steps to integrate Require.js into your project
###Setup the MAC OSX Apache Web Server
- Open the project file,
index.html
with web server and view space.localhost in the browser - Move the project folder to MAC OSX Sites folder
- Start MAC OCX’s built-in Apache Web Server by opening System Preferences > Sharing > check Web Sharing
- Edit the hosts file located at
/private/etc/hosts
with the line127.0.0.1 space.localhost
- Ensure line
Include /private/etc/apache2/extra/httpd-vhosts.conf
is uncommented in the file/private/etc/apache2/httpd.conf
- 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
</Directory>
</VirtualHost>
View space.localhost in the browser
###Steps to integrate require.js
- Download require.js file in the
js
folder - 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 thehead
tag. - Create
config.js
andmain.js
and edit them accordingly
##More Resources on Require.js
- What is AMD?
- Writing Modular JavaScript With AMD, CommonJS & ES Harmony by Addy Osmani
- How to structure your app using require.js
- Modular Javascript
- require.js 3 part series screencast by Cary Landholt
- Other example for your script loading needs
##Build Link of this Episode
jQuery Fundamentals by Jessica Murphey
##Credits
Thanks to Sebastiaan and Thomas for RequireJS advice