Time for action – optimizing JavaScript with Require.js

Follow these steps to optimize the source code of your app using Node.js and Require.js:

  1. Install the require.js module using npm from the command-line tool.
    $ sudo npm install requirejs -g
    
  2. Go to the root folder of the app you worked on in Chapter 4, Architecting Your Mobile App, create a file named build.js, and add to it the build process configuration info (i.e., the JavaScript folder, the paths to the library used in the project, the name of the main file of the app, and the output folder and filename).
    ({
        baseUrl: 'js/',
        paths: {
            mustache: 'libs/mustache',
            alice: 'libs/alice.min',
            text: 'libs/require/plugins/text'
        },
        name: 'main',
        out: 'js/main-built.js'
    })
  3. Open the command-line tool again and execute the following command in order to build the app:
    $ r.js -o build.js
    
  4. Open the index.html file and change the entry point of your app in the script tag in the header.
    <script data-main="js/main-built" src="js/libs/require/require.js"></script>
  5. Open the index.html file in a browser.

What just happened?

You created a compressed version of the app JavaScript files minified in a single file specifying the command-line options using a build file. The result is that the code of the app is now optimized using UglifyJS2 (the engine that works behind the scenes) and it still works perfectly. In order to get a complete overview of the build options, refer to the sample build file available on GitHub at https://github.com/jrburke/r.js/blob/master/build/example.build.js.

Tip

If you prefer to use the Closure Compiler to compress and optimize the app JavaScript files, you have to download the binaries of Rhino (an open-source implementation of JavaScript written entirely in Java) available at https://developer.mozilla.org/en-US/docs/Rhino/Download_Rhino, download r.js from the Require.js website at http://requirejs.org/docs/download.html#rjs, add the optimize: 'closure' option to the build file, and execute the following command:

$ java -classpath ~/rhino1_7R4/js.jar:~/compilers/closure-compiler/compiler.jar org.mozilla.javascript.tools.shell.Main r.js build.js

Where classpath refers to the full path to Rhino and the Closure Compiler.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.82.23