Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RequireJS in 15 Minutes

RequireJS in 15 Minutes

A quick intro to RequireJS

Matthew Dapena-Tretter

October 11, 2013
Tweet

More Decks by Matthew Dapena-Tretter

Other Decks in Programming

Transcript

  1. The Old Way •Dependencies defined out-of-band •Lots of script tags

    (& requests) •…or a very very big main.js •…or a build step in development •All files load synchronously
  2. With RequireJS ? Dependencies defined out-of-band ? Lots of script

    tags (& requests) ? …or a very very big main.js ? …or a build step in development ? All files load synchronously
  3. Module IDs (Not Paths) in Array Correspond to Arguments require(['jquery',

    'jquery.plugin'], function ($) { // Main code goes here });
  4. Write Your Own Modules! define(['jquery', 'jquery.plugin'], function ($) { function

    makeButton (el) { $(el).click(function () { alert('I was clicked!'); }); } return makeButton; });
  5. Use define() to Declare Dependencies For Modules define(['jquery', 'jquery.plugin'], function

    ($) { function makeButton (el) { $(el).click(function () { alert('I was clicked!'); }); } return makeButton; });
  6. Dependencies Work the Same as With require() define(['jquery', 'jquery.plugin'], function

    ($) { function makeButton (el) { $(el).click(function () { alert('I was clicked!'); }); } return makeButton; });
  7. Return the Module From the Function define(['jquery', 'jquery.plugin'], function ($)

    { function makeButton (el) { $(el).click(function () { alert('I was clicked!'); }); } return makeButton; });
  8. Alternative Syntax Improves Long Dependency Lists define(function (require) { var

    $ = require('jquery'); require('jquery.plugin'); function makeButton (el) { $(el).click(function () { alert('I was clicked!'); });
  9. Use Your Module in Other Modules or Scripts define(function (require)

    { var makeButton = require('makebutton'); makeButton('#element'); . . . . .
  10. Module IDs Are Based on File Names… define(function (require) {

    var makeButton = require('makebutton'); makeButton('#element'); . . . . .
  11. …But Don’t Use Paths! That’s What Config is For require.config({

    paths: { makebutton: 'path/to/makebutton' } });
  12. …And For “Shimming” Scripts That Don’t Use AMD require.config({ shim:

    { underscore: { deps: ['jquery'], exports: '_' } }, paths: {
  13. With RequireJS •Dependencies defined out-of-band •Lots of script tags (&

    requests) •…or a very very big main.js •…or a build step in development •All files load synchronously
  14. Use r.js Optimizer For Production •Module-aware concatenation •Can build one

    file or many $ node r.js -o name=main out=main-built.js
  15. With RequireJS •Dependencies defined out-of-band •Lots of script tags (&

    requests) •…or a very very big main.js •…or a build step in development •All files load synchronously