Frage

I have a module that just executes some code in order to overwrite some existing functionality. The module doesn't return any value. It looks a bit like this:

// module "patch.js"
define(function (require) {
    var lib = require("lib");
    lib.foo = function () {
        // overwrite foo function here
    }
});

I then define it as a dependency of my main app module, something like this:

// main.js
require.config({
    shim: {
        "app": {
            deps: ["patch"]
        }
    }
});

And then I kick off the app module like this:

// main.js
require(["app"],function (app) {
    app.start();
});

This works fine when running the unoptimised version. The "patch" module is loaded before app starts and the code inside it is invoked. All is well.

The problem starts when I optimise using r.js. I'm noticing that the "patch" module's code is being pulled into the optimised file but is never being invoked.

I can force it to invoke by explicitly calling require("patch") somewhere in my app code, but I'd rather just define this dependency in the config.

What's the reason for this difference in behaviour between un-optimised and optimised modules? Why is the unoptimised module automatically invoked, whereas the optimised module is included in the built file but never invoked? Can I work around it with config options? Can I change the way I'm defining my "patch" module to get the behaviour I'm after?

== EDIT: Adding r.js config ==

I'm using grunt-contrib-requirejs. The config is about as simple as it gets.

{
    baseUrl: "site/js",
    mainConfigFile: "site/js/main.js",
    out: "build/js/main.js",
    name: "main",
    optimize: "uglify2",
    removeCombined: false
}
War es hilfreich?

Lösung

A couple of things to point out

  1. Shim config should be used only for NON-AMD modules. For instance you're trying to integrate a jQuery plugin that is not defined inside a define function. So this segment of code is not necessary and can even break your app:

    require.config({
        shim: {
            "app": {
                deps: ["patch"]
            }
        }
    });
    
  2. Second, try to define the modules in your app in the r.js optimizer

    {
        baseUrl: "site/js",
        mainConfigFile: "site/js/main.js",
        out: "build/js/main.js",
        name: "main",
        optimize: "uglify2",
        removeCombined: false,
        modules : [
            {
                name : 'site/js/main.js'
            }
        ]
    }
    

In this way r.js will know how to bundle the main.js module and all of its dependencies correctly.

Hope this helps.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top