modular javascript using require

Upload: manojays-directionone

Post on 03-Jun-2018

239 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Modular Javascript Using Require

    1/22

    home quick answers discussions features community

    helpSearch for articles, questions, tips

    Articles Desktop Development Miscellaneous General

    Article

    Browse Code

    Bugs/ Suggestions

    Stats

    Revisions (2)

    Alternatives

    Comments (25)

    View this article's

    Workspace

    Fork this Workspace

    About Article

    A look at creating well

    structured modularjavascript using AMD libraryRequire.js

    Type Article

    Licence CPOL

    First Posted 2 Jul 2013

    Views 37,727Bookmarked 32 times

    ASP Architec t Dev

    Intermediate jQuery , +

    Next

    Rate:

    Modular Javascript Using Require.JsBy Sacha Barber, 2 Jul 2013

    Download demo project: RequireJsDemos.zip

    Introduction

    The Problem

    A Possible Solution

    The Demos

    Simple Demo

    Bootstrapping an app to use Require.js

    Using require() vs. define()

    Using With jQuery

    Using With ASP .NET MVC (4)

    Using With TypeScript

    Type Script Definition FilesUse the AMD Module Command Line

    5.00 (15 votes)

    Sign up for our free weekly Web Developer Newsletter.

    articles

    https://workspaces.codeproject.com/sacha-barber/modular-javascript-using-require-jshttps://workspaces.codeproject.com/sacha-barber/modular-javascript-using-require-jshttp://www.codeproject.com/script/Articles/ViewTasks.aspx?aid=614507http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=614507http://www.codeproject.com/KB/FAQs/http://www.codeproject.com/script/Membership/View.aspx?mid=569009http://www.codeproject.com/Chapters/1/Desktop-Development.aspxhttp://www.codeproject.com/KB/miscctrl/http://www.codeproject.com/KB/miscctrl/#Generalhttp://www.codeproject.com/script/Answers/List.aspx?tab=activehttp://www.codeproject.com/http://www.codeproject.com/http://www.codeproject.com/http://www.codeproject.com/feature/web-newsletterhttps://workspaces.codeproject.com/sacha-barber/modular-javascript-using-require-jshttp://www.codeproject.com/script/Articles/Latest.aspxhttp://www.codeproject.com/feature/web-newsletterhttp://www.codeproject.com/KB/miscctrl/614507/RequireJsDemos.ziphttp://www.codeproject.com/script/Membership/View.aspx?mid=569009http://www.codeproject.com/script/Articles/PrevNextLookup.aspx?aid=614507&at=1&secId=14http://www.codeproject.com/script/common/TellFriend.aspx?obtid=2&obid=614507http://www.codeproject.com/Articles/614507/Modular-Javascript-Using-Require-Js?display=Printhttp://www.codeproject.com/Tags/jQueryhttp://www.codeproject.com/Tags/Intermediatehttp://www.codeproject.com/Tags/Devhttp://www.codeproject.com/Tags/Architecthttp://www.codeproject.com/Tags/ASPhttp://www.codeproject.com/info/cpol10.aspxhttp://www.codeproject.com/script/Articles/Types.aspx?#Articlehttps://workspaces.codeproject.com/sacha-barber/modular-javascript-using-require-js/forkhttps://workspaces.codeproject.com/sacha-barber/modular-javascript-using-require-jshttps://workspaces.codeproject.com/sacha-barber/modular-javascript-using-require-jshttp://www.codeproject.com/Articles/614507/WebControls/#_commentshttp://www.codeproject.com/script/Articles/ListAlternatives.aspx?aid=614507http://www.codeproject.com/script/Articles/ListVersions.aspx?aid=614507http://www.codeproject.com/script/Articles/Statistics.aspx?aid=614507http://www.codeproject.com/script/Articles/ViewTasks.aspx?aid=614507http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=614507http://www.codeproject.com/script/Bookmarks/Add.aspx?obid=614507&obtid=2&action=AddBookmark&bio=true&bis=largehttp://www.codeproject.com/KB/miscctrl/#Generalhttp://www.codeproject.com/KB/miscctrl/http://www.codeproject.com/Chapters/1/Desktop-Development.aspxhttp://www.codeproject.com/script/Content/SiteMap.aspxhttp://www.codeproject.com/KB/FAQs/http://www.codeproject.com/Lounge.aspxhttp://www.codeproject.com/Feature/http://www.codeproject.com/script/Forums/List.aspxhttp://www.codeproject.com/script/Answers/List.aspx?tab=activehttp://www.codeproject.com/http://www.codeproject.com/
  • 8/12/2019 Modular Javascript Using Require

    2/22

    Connect using Git

    Add your ownalternative version

    Share

    Top News

    China bans use of

    Microsoft's Windows 8 on

    government computers

    Get the Insider Newsfree eachmorning.

    Related Videos

    Related Articles

    Angular.js example application

    Making the most out ofJavaScript Intellisense in VS2012

    #javascript Require.js vs

    CommonJS / AMD modulesand #angularjs

    Introduction to ASP.NETBoilerplate

    Don't Use the AMD Module Command Line (CommonJS Style)

    That's It

    Introduction

    I don't know how many of you use lots of JavaScript libraries, but we found ourselves using

    quite a lot within certain projects. One of the strange issues that came about from linkingJavaScript files was that we occasionally ran into dependency issues, where by a particular

    JavaScript source file would have a dependency on another JavaScript source file that was not

    loaded (and therefore not available) yet.

    As luck would have it there is an excellent library for dealing with interlinked JavaScript

    dependencies and module loading which is called : RequireJs

    The Problem

    You may be asking what problem RequireJsis attempting to solve. Well lets consider a most

    common example, which is that of a custom jQuery plugin, where jQuery MUST be loaded

    before the plugin will work. If we stuck to using standard script tags something like this

    Collapse | Copy Code

    We instantly have a problem, our custom jQuery plugins will not work, as jQuery itself has not

    be loaded yet. Sure we could move the jQuery script tag to be before the custom jQuery

    plugins, which would indeed fix the problem this once. This is however a very isolated small use

    case, which is not really the norm on large scale applications, where we may have many many

    related files which all have dependencies. This is where RequireJscan help. Want to know more,

    read on.

    http://requirejs.org/http://requirejs.org/http://requirejs.org/http://-/?-http://-/?-http://www.codeproject.com/Articles/768664/Introduction-to-ASP-NET-Boilerplatehttp://www.codeproject.com/Articles/745030/sharpjavascript-Require-js-vs-CommonJS-AMD-moduleshttp://www.codeproject.com/Articles/460836/Making-the-most-out-of-JavaScript-Intellisense-inhttp://www.codeproject.com/Articles/637430/Angular-js-example-applicationhttp://codeproject.tv/video/5001191/javascript_if_statementhttp://codeproject.tv/video/5001188/javascript_switch_statementhttp://www.codeproject.com/Feature/Insider/http://www.reuters.com/article/2014/05/20/us-microsoft-china-idUSBREA4J07Q20140520http://www.codeproject.com/script/Articles/SubmissionWizard.aspx?at=1&apid=614507http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=614507
  • 8/12/2019 Modular Javascript Using Require

    3/22

    JavaScript Frameworks andResources

    Quick JavaScript OO (Object

    Orientation) Primer

    ElmahR = ELMAH + SignalR(1.0.0 released!)

    Implementing RequireJs on

    BackboneJsCase Study Implementing an

    HTML5/Javascript EnterpriseJava Application

    #javascript Require.js vs

    CommonJS / AMD modulesand #angularjs

    RSA Interoperability between

    JavaScript andRSACryptoServiceProvider -

    Form Login ExampleWriting modular JavaScriptwithout polluting the global

    namespace

    Challenges and solutions -Architecture of a Modern Web

    Application - Part 1

    Create String Variable from TextFile Source

    Adding a Build Banner to

    ASP.NET PagesChapter 5: Creating Web Widget

    with HTML, CSS, and JavaScript

    Getting Started with theRequireJS Library

    Encryption - RSA implementedthrough Java Script toEncryt/Decrypt data

    Performance Optimization ofASP.NET Applications on

    Client-side

    ASP.NET MVC4: Bundling and

    A Possible Solution

    So now that you know the problem what is a possible solution? Well as I have already stated

    this article will use RequireJsa one viable solution to the problem just described. RequireJsdoes

    a bit more than just solve dependencies, it also provides asynchronous module and file loaded.

    In my mind the fact that RequireJsuses modules is a very good thing, as it gives a guiding

    push to the developer, which should nudge them into creating a module which has a singleresponsibility which is never a bad thing. Using RequireJswe are able to specify things like:

    Define a module

    Require a module

    The modules dependencies (via a RequireJsconfig called shim)

    The module paths

    The Demos

    This section will outline several different RequireJsexamples, starting with a typical simple use

    case, and then building on to slightly more complex examples.

    Simple Demo

    This is the simple basic 101 sample, and it illustrates the very basics of using RequireJs. This will

    be expanded upon later, but it does illustrate a few key points that we will come across in later

    examples.

    Here is what the structure of this project looks like in Visual Studio:

    http://requirejs.org/http://requirejs.org/http://requirejs.org/http://requirejs.org/http://requirejs.org/http://requirejs.org/http://requirejs.org/http://www.codeproject.com/Tips/389545/ASP-NET-MVC-Bundling-and-Minificationhttp://www.codeproject.com/Articles/31796/Performance-Optimization-of-ASP-NET-Applications-ohttp://www.codeproject.com/Articles/4959/Encryption-RSA-implemented-through-Java-Script-tohttp://www.codeproject.com/Articles/625262/Getting-Started-with-the-RequireJS-Libraryhttp://www.codeproject.com/Articles/81355/Chapter-Creating-Web-Widget-with-HTML-CSS-and-Jahttp://www.codeproject.com/Articles/23291/Adding-a-Build-Banner-to-ASP-NET-Pageshttp://www.codeproject.com/Articles/7292/Create-String-Variable-from-Text-File-Sourcehttp://www.codeproject.com/Articles/645753/Challenges-and-solutions-Architecture-of-a-Modernhttp://www.codeproject.com/Articles/342938/Writing-modular-JavaScript-without-polluting-the-ghttp://www.codeproject.com/Articles/11479/RSA-Interoperability-between-JavaScript-and-RSACryhttp://www.codeproject.com/Articles/777641/sharpjavascript-Require-js-vs-CommonJS-AMD-modulhttp://www.codeproject.com/Articles/545049/CaseplusStudyplus-e-plusImplementingplusanplhttp://www.codeproject.com/Articles/378116/Implementing-RequireJs-on-BackboneJshttp://www.codeproject.com/Articles/377394/ElmahR-equals-ELMAH-plus-SignalR-releasedhttp://www.codeproject.com/Articles/514270/QuickplusJavaScriptplusOOplus-ObjectplusOrientatiohttp://www.codeproject.com/Articles/596800/JavaScript-Frameworks-and-Resources
  • 8/12/2019 Modular Javascript Using Require

    4/22

    Minification

    Related Research

    Ten Tips of Web App Testing

    Best Practices for Securing Your

    Private Keys and Code SigningCertificates

    Essential Keys to MobileUsability

    Bootstrapping an app to use Require.js

    One of the things you must do with RequireJsis to tell it which file will be used for the overall

    configuration. Here is a simple example

    Collapse | Copy Code

    My Sample Project

    You can see that the data-main attribute points to a main file which is what sets up the

    RequireJsconfiguration. Lets see a simple example of this shall we:

    Collapse | Copy Code

    (function() {

    require(["app/data", "helper/util", "helper/logger"], function(data, util,logger) {

    //This function is called when scripts/helper/util.js is loaded. //If util.js calls define(), then this function is not fired until

    http://requirejs.org/http://requirejs.org/http://www.codeproject.com/ResearchLibrary/46/Essential-Keys-to-Mobile-Usabilityhttp://www.codeproject.com/ResearchLibrary/25/Best-Practices-for-Securing-Your-Private-Keys-andhttp://www.codeproject.com/ResearchLibrary/45/Ten-Tips-of-Web-App-Testinghttp://www.codeproject.com/Tips/389545/ASP-NET-MVC-Bundling-and-Minification
  • 8/12/2019 Modular Javascript Using Require

    5/22

    How to Secure Your Software

    for the Mobile Apps Market

    //util's dependencies have loaded, and the util argument will hold

    //the module value for "helper/util".

    alert('util module : '+ util.doubleItMethod(10));

    //This function is called when scripts/app/data.js is loaded.

    //If data.js calls define(), then this function is not fired until

    //data's dependencies have loaded, and the util argument will hold //the module value for "app/data".

    alert('data module [0] : '+ data.storedData[0]); alert('data module [1] : '+ data.storedData[1]);

    logger.logThePair(); });

    })();

    What we can see there is the use of the require()function, which is what RequireJsgives us.

    The 1st parameter (which may be an array as shown) specifies the dependencies that this

    function has. Lets now focus our attention on one of those modules that we have a

    dependency on.

    This following snippet is the logger module, and note above how we state that we

    require()the logger module, which RequireJsgives us, and then are free to use the modules

    code. Which again can be seen above where we use the logger modules logThePair( )

    function

    Collapse | Copy Code

    define(function(require) { varpair = require(".././app/keyValuePairs");

    return{ logThePair: function() { alert("color: "+ pair.color + ", size: "+ pair.size); } };});

    In this example we define a module using define()and we also take in RequireJswhich gets

    special treatment, where RequireJsknows what to do with it. We are now able to use this

    defined module using another require()call somewhere else, which we saw above when we

    wrote out

    http://requirejs.org/http://requirejs.org/http://requirejs.org/http://requirejs.org/http://www.codeproject.com/ResearchLibrary/30/How-to-Secure-Your-Software-for-the-Mobile-Apps-Ma
  • 8/12/2019 Modular Javascript Using Require

    6/22

    Collapse | Copy Code

    require(["app/data", "helper/util", "helper/logger"], function(data, util,logger) {....}

    One thing of note there is the path is also included "helper/logger" so require will look for a file

    that matches that path and use that. We can also specify paths like this

    Collapse | Copy Code

    define(function(require) { varpair = require(".././app/keyValuePairs");

    return{ logThePair: function() { alert("color: "+ pair.color + ", size: "+ pair.size); } };});

    We will see more on path configuration later

    Using require () vs. define()

    We can use both require()and define()to load module dependencies. The require()

    function is used to run immediately, where as define()is used to define modules which may

    be used from multiple locations.

    Using With jQuery

    So now that we have seen a trivial example of using RequireJslets continue our journey. Lets

    see what it takes to create an example where we have actually library depenencies, such as a

    http://requirejs.org/
  • 8/12/2019 Modular Javascript Using Require

    7/22

    jQuery plugin that needs jQuery in order for function.

    Here is what the structure of this project looks like in Visual Studio:

    As before we start (as we always will) by telling RequireJsthe main javascript code file to

    boostrap the app

    Collapse | Copy Code

    jQuery+RequireJS Sample Page jQuery+RequireJS Sample Page

    Where the scripts/app javascript file looks like this

    Collapse | Copy Code

    http://requirejs.org/
  • 8/12/2019 Modular Javascript Using Require

    8/22

    // Place third party dependencies in the lib folder

    //

    // Configure loading modules from the lib directory,

    // except 'app' ones,

    requirejs.config({ "baseUrl": "scripts/lib", "paths": { "app": "../app" },

    "shim": { "jquery.appender": ["jquery"], "jquery.textReplacer": ["jquery"],

    }});

    // Load the main app module to start the app

    requirejs(["app/main"]);

    This time we can see something new. We can see that we are actually configuring RequireJsfor

    certain things, such as:

    1. BaseUrl : Specifies the base path for all the scripts, you can still use RequireJswith relative

    paths, but this is its base path

    2. Paths : Is a map of named paths where we specify a well known name and a path

    3. Shim : Is a map of files, and their dependecies. What this does is that is gives a hint to

    RequireJsabout the required module dependencies such that RequireJswill then know to

    load them in the correct order. Remember that RequireJsuses a technique which means

    modules are loaded asychronously. It can be seen from the example above that

    "jquery.appender" and "jquery.textReplacer" are dependent on jQuery. As such RequireJs

    will load that first.It may seem that we are just swapping the evils of having the correct

    javascript imports in the html in the correct order for this, but what we do get from

    RequireJsis that modules are loaded asychronously

    The last point is that we then kick of the whole app by telling RequireJswihch is the initial app

    file that should be run. This is done using the line

    Collapse | Copy Code

    // Load the main app module to start the app

    requirejs(["app/main"]);

    http://requirejs.org/http://requirejs.org/http://requirejs.org/http://requirejs.org/http://requirejs.org/http://requirejs.org/http://requirejs.org/http://requirejs.org/
  • 8/12/2019 Modular Javascript Using Require

    9/22

    So lets examine that file for a minute

    Collapse | Copy Code

    require(["jquery", "jquery.appender", "jquery.textReplacer"], function($) { //the jquery.appender.js plugin have been loaded.

    $(function() { $(document).ready(function() { $('#btn').click(function() { varold = $('#txt').val() varrev = reverseString(old); $('h1').replaceTextWithFade('Old text was : '+ old); $('body').appendData(rev); }); }); });

    functionreverseString(str) { if(typeofstr !== 'string') { thrownewError('reverseString(str) accepts only strings.'); return; }

    varstrArr = str.split('');

    varreversed = strArr.reverse(); returnreversed.join(''); };});

    It can be seen that is uses jQuery and the 2 custom jQuery plugins, that have by magic had

    their dependency on jQuery satisfied by RequireJs, so we can now safely use them within the

    javascript that asked for them as requirements.

    Just for completeness here is one of the custom jQuery plugins that the code above makes use

    of

    Collapse | Copy Code

    (function($) { $.fn.appendData = function(data) { this.each(function() { returnthis.append('

    '+ data + '

    '); }); }}(jQuery));

    RequireJsmagically makes sure that this is not loaded until jQUery itself is loaded, at which poit

    http://requirejs.org/http://requirejs.org/
  • 8/12/2019 Modular Javascript Using Require

    10/22

    it will be provided to these plugins

    Using With ASP .NET MVC (4)I also wanted to demonstrate how to use RequireJswithin a ASP .NET MVC application (I chose

    MVC 4). and here is how I did it.

    Here is what the structure of this project looks like in Visual Studio:

    http://requirejs.org/
  • 8/12/2019 Modular Javascript Using Require

    11/22

  • 8/12/2019 Modular Javascript Using Require

    12/22

    I used the same boostrapper "app.js" code that we saw above, and the same 2 custom jQuery

    plugins, that we just saw.

    So now that you know are using some of the same stuff we just saw, lets proceed to the ASP

    .NET MVC 4 specific bits shall we.

    It starts with the Bundle.Config file which for me is as follows;

    Collapse | Copy Code

    publicclassBundleConfig{ publicstaticvoidRegisterBundles(BundleCollection bundles) { bundles.Add(newScriptBundle("~/bundles/lib").Include( "~/Scripts/Lib/require.js"));

    bundles.Add(newStyleBundle("~/Content/css").Include("~/Content/site.css")); }}

    And then we have a master layout page which makes use of the bundles like this:

    Collapse | Copy Code

    @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/lib") @RenderSection("scripts", required: false) ..... ..... .....

    However this time since we are relying on ASP .NET MVC 4s bundling capabilities we need toprovide a separate link to the boostrapper for RequireJs, which is done as follows:

    http://requirejs.org/
  • 8/12/2019 Modular Javascript Using Require

    13/22

    Collapse | Copy Code

    Where app.jsis the same as the previous example.

    From there all that is left to do is to declare what scripts you want per page (which is typical for

    any ASP .NET MVC app)

    Collapse | Copy Code

    @{ ViewBag.Title = "Home Page";}................@section Scripts { }

    ........

    ....

    ....

    Which we can then create a standard javascipt file such as the following

    Collapse | Copy Code

    require(["jquery", "common/Utils", "jquery.appender", "jquery.textReplacer"],function($,

    common) {

    $(document).ready(function() {

    $('#mainDiv').append('

    Index page is working with Require.js

    '); alert('Type some text into the text box and then click the button');

    $('#btn').click(function() { varold = $('#txt').val() varrev = common.reverseString(old); $('#appendToDiv').appendData(rev); }); });

    });

  • 8/12/2019 Modular Javascript Using Require

    14/22

    Which is specific for the controller/page combo and will be injected into the "Scripts" section of

    the layout page.

    Using With TypeScript

    Typescriptis the new kid on the block and is Microsofts attempt at proding OO like features to

    JavaScript. Typescriptessentially has its own compiler which take a Typescriptfile (*.ts) and

    compiles that to a JavaScript file (*.js). I thought for completeness I should also cover

    Typescript, though this only covers how to use RequireJswith Typescript.

    Here is what the structure of this project looks like in Visual Studio:

    Before we start I should mention that when working with Typescriptyou MOSTdefinately want

    http://www.typescriptlang.org/http://www.typescriptlang.org/http://requirejs.org/http://www.typescriptlang.org/http://www.typescriptlang.org/http://www.typescriptlang.org/http://www.typescriptlang.org/
  • 8/12/2019 Modular Javascript Using Require

    15/22

    to install the Web Essential Visual Studio Extensionwhich makes working with Typescriptso

    much better. It provides a Typescriptitem template for Visual Studio. When the compilation

    process is kicked off it will also create the JavaScript for the Typescriptfile as well.

    Type Script Definition Files

    One of the nice things about Typescriptis that is will moan at save time (with the Web Essential

    Visual Studio Extensionsinstalled) if you do not have the appropriate definition files loaded.

    Here is an example of that :

    Click for larger image

    Luckily help is at hand by way of the awesome set of definition files that are available for all the

    major JavaScript libraries out there.

    You just need to head over to the DefinitelyTyped web sitewhich has definition files for

    Typescriptof all the major JavaScript libraries out there. Here is an example of what it looks like

    with the correct definition files loaded, see how the compile errors have gone. Oh all I did was

    include the correct definition files from the DefinitelyTyped web siteand included them in the

    the project and dragged them onto the Typescriptfile.

    http://www.typescriptlang.org/https://github.com/borisyankov/DefinitelyTypedhttp://www.typescriptlang.org/https://github.com/borisyankov/DefinitelyTypedhttp://www.codeproject.com/KB/miscctrl/614507/TS2Big.pnghttp://visualstudiogallery.msdn.microsoft.com/07d54d12-7133-4e15-becb-6f451ea3bea6http://www.typescriptlang.org/http://www.typescriptlang.org/http://www.typescriptlang.org/http://www.typescriptlang.org/http://visualstudiogallery.msdn.microsoft.com/07d54d12-7133-4e15-becb-6f451ea3bea6
  • 8/12/2019 Modular Javascript Using Require

    16/22

    Click for larger image

    There is one last thing that I wanted to mention when using Typescriptand RequireJstogether,which is a command line argument that MUST be provided to work with RequireJscorrectly.

    http://requirejs.org/http://requirejs.org/http://www.typescriptlang.org/http://www.codeproject.com/KB/miscctrl/614507/TS1Big.png
  • 8/12/2019 Modular Javascript Using Require

    17/22

    This is the module type which can either be "commonJS" or "amd". "commonJS" would be used

    if you were doing node development, whilst "amd" would be used when you are doing things

    like RequireJs. By the way amd stands for "Asynchronous Module Definition".

    There is a really nice article available here which has some more information avaiable on the

    differences between "commonJS" and "amd" modular javascript:

    http://addyosmani.com/writing-modular-js/

    http://addyosmani.com/writing-modular-js/http://requirejs.org/
  • 8/12/2019 Modular Javascript Using Require

    18/22

    Luckily installing the eb Essential Visual Studio Extensionmakes things a lot easier for us, as all

    we need to do is go set an Option in Visual Studio and the correct command line will be

    emitted for us.

    Anyway enough of all the background stuff, let's see some code shall we.

    This is the raw html demo page

    Collapse | Copy Code

    TypeScript HTML App

    TypeScript HTML App

    http://visualstudiogallery.msdn.microsoft.com/07d54d12-7133-4e15-becb-6f451ea3bea6
  • 8/12/2019 Modular Javascript Using Require

    19/22

    Where is can be seen that we use the same stuff as before where we link through to a

    scripts/app bootstrapper file. This bootstrapping file is shown below. It is largely the same as

    previous examples but we are of course able to make use of some of Typescripts features such

    as lambdas ( () => ). You can click the image below to see a larger version of what JavaScript

    gets created. Like I say it is largely the same as the previous examples:

    Click for larger image

    So now that we have a bootstrapper in place, lets look at the main app.js file.

    I just wanted to show you the difference between what the Typescriptcompiler would do

    depending on the command line option for picking your module type that we discussed earlier,

    before we talk about the nitty gritty of using RequireJs(although if you just read the code

    below, you can see it clearly):

    Use the AMD Module Command Line

    This is what would be compiled (the JavaSript is on the right hand side) with the AMD

    command line arg turned on.

    http://requirejs.org/http://www.typescriptlang.org/http://www.codeproject.com/KB/miscctrl/614507/TS1Big.pnghttp://www.typescriptlang.org/
  • 8/12/2019 Modular Javascript Using Require

    20/22

    Click for larger image

    Don't Use the AMD Module Command Line (CommonJS Style)

    This is what would be compiled (the JavaSript is on the right hand side) with the AMD

    command line arg turned off.

    Click for larger image

    See how its quite different. In fact using the "amd" command line argument causes the

    Typescriptcompiler to actually use RequireJssyntax.

    Anyway to use RequireJsinside of a Typescriptfile is pretty easy, all you have to do, is make

    sure the Typescriptfile knows about the correct RequireJsdefinition file (which we talked about

    earlier) and then start using RequireJs.

    Here is small example:

    Collapse | Copy Code

    http://requirejs.org/http://requirejs.org/http://www.typescriptlang.org/http://www.typescriptlang.org/http://requirejs.org/http://requirejs.org/http://www.typescriptlang.org/http://www.codeproject.com/KB/miscctrl/614507/TS5CommonJSBig.pnghttp://www.codeproject.com/KB/miscctrl/614507/TS5AMDBig.png
  • 8/12/2019 Modular Javascript Using Require

    21/22

    require(['jquery'], ($) => { varel = $('#content'); vargreeter = newgt.Greeter(el); greeter.start();});

    I am using a vriation of the Greeterexample as shown on the Typescriptweb site, where we

    simple update a DOM element. There is one thing to be aware of since I also wanted to use

    jQuery to pick out the HtmlElement to pass to the Greeter you are then forced into using

    the Typescripttype any, as it does not recognize a jquery wrapped HtmlElement as a

    HtmlElement type.

    Anyway here is the code for the Greeter:

    Click for larger image

    http://www.codeproject.com/Articles/614507/TS6SBig.pnghttp://www.typescriptlang.org/http://www.typescriptlang.org/
  • 8/12/2019 Modular Javascript Using Require

    22/22