Chad Johnson
Chad Johnson

Reputation: 21905

RequireJS with multiple pages -- using optimizer

I have my JavaScript organized as described here: https://stackoverflow.com/a/10816983/83897.

I have a JavaScript-heavy ASP.NET application that has multiple different pages (vs. being a single-page application). Each page has different dependencies, so I have a per-page .js file (page1.js, page2.js, etc.). Each has a require() call, declaring its dependencies:

require(['jquery', 'page1Module'], function($, module){
    // page1 specific stuff here
});

This works fine. What I'm wondering is, how might the RequireJS build process work? I think I want a per-page "build" .js file (e.g. page1-build.js, page2-build.js, etc.)? Is there existing software I can leverage?

The process might look like this:

  1. Compile all dependencies for a given script into one build.js file in a temporary directory.
  2. Calculate an MD5 fingerprint for the compiled file.
  3. Compare that fingerprint with the comparable file in public/assets.
  4. Create an in-memory RequireJS manifest, mapping each module to the compiled file. Append this manifest to the compiled file.
  5. Somehow make production use the build file.

EDIT: After some thought, I'm thinking the RequireJS optimization using node + r.js will just be part of a larger asset building process, where the asset building relies on some other, third-party library. The RequireJS optimization will simply be used for certain JavaScript dependencies (i.e. the JavaScript files for each page, including found dependencies), perhaps specified in some XML config.

Upvotes: 4

Views: 2935

Answers (1)

Marcelo De Zen
Marcelo De Zen

Reputation: 9507

You can create multiple optimized files by specifing the modules in the build profile:

{
   modules: [
     {
         name: "main"
     },
     {
        name: "page1",
        include: ["dep1", "shim2"],
        exclude: ["main"]
     }]
}

Each entry will generate a optmized .js file.

More info here: How to use RequireJS build profile + r.js in a multi-page project

Upvotes: 3

Related Questions