Search code examples
javascriptrequirejsr.js

How to optimize a subset of JavaScript files created as RequireJS modules


I have single-page web application that uses RequireJS to organize and structure JavaScript code. Inside the app, I have some JS files that I want to optimize using r.js because they belong to an API that will be consumed by my customers. So, I just want to optimize those files and keep the rest of the code as it is now.

This is my application structure:

  • app
    • main.js
    • many other files and folders
  • scripts
    • myAPI
      • app.js
      • many other files and folders
    • require.js
    • jquery.js
    • build.js
  • index.htm

All the JavaScript code is located under the app and scripts folders. As I mentioned before, all those files are defined as RequireJS modules. This is how the main.js looks now:

require.config({
    baseUrl: 'scripts',
    paths: {
        base: 'myAPI/base',
        proxy: 'myAPI/proxyObject',
        localization: 'myAPI/localization',
        app: '../app',
    }

});
require(['myAPI/app'],
    function (app) {
        //app.init....
    }
);

As you can see, in the paths configuration I'm defining some aliases that point to myAPI (the folder I want to optimize).

This is how I reference RequireJS from the index.htm file:

<script data-main="app/main" src="scripts/require.js"></script>

This is the build file I created for r.js (scripts/build.js):

({
   baseUrl: '.',
   out: 'build/myAPI.js',

   name: 'myAPI/app',
   include: ['some modules'],
   excludeShallow: ['some modules defined in the app folder'],

   mainConfigFile: '../app/main.js',
   optimize: 'uglify2',
   optimizeCss: 'none'
})

The optimized file is generated, but I have some challenges trying to use it:

  1. How do I reference that file from the app?
  2. The dependencies to myAPI modules are broken now. RequireJS doesn't find the modules defined in myAPI.
  3. What can I do to keep the aliases defined in require.config.paths working?

Could you please help me with some suggestions or feedback for this situation?

Thanks!!


Solution

  • After doing research, I could solve my problem. I based my solution in this Github project created by James Burke: https://github.com/requirejs/example-libglobal.

    First, I had to remove all the dependencies to myAPI individual modules, and create an object that centralizes the access to any internal dependency. Then, I created a r.js script to generate a single file for myAPI. That file is the one that will consumed by the other JS files. That single file can be referenced as a global object or as an AMD module, as James Burke shows in the Github project.

    The aliases defined in require.config.paths were no longer necessary.