4

I have a web application that uses Require in order to load dependencies. I have a set of JS libraries that are included using the Require config.shim object.

Two such example libraries are:

require.config({
  shim: {
    "libs/leaflet": {
        exports: "L"
    }  
    "libs/leaflet-dvf": {
        deps: ["libs/leaflet"],
        exports: "L"
    }
}

The second library, leaflet-dvf requires the first, leaflet. The second is a plugin to the first that depends on the global scope variable L that the first library defines.

When I run the application using Require normally, everything works fine. I can include either library from the shim, and everything works great. No problems.

The problem comes when I run this code through the Require r.js Optimizer. The Optimizer, when it builds the single optimized JS file, will incorrectly order the dependencies. In the built file, the leaflet-dvf code will come before the leaflet code. This causes a JS runtime error because the dependant plugin cannot find the L global scope variable that is required.

My build config looks like:

({
  baseUrl: "../js",
  paths: {
    "requireLib": "../js/libs/require"
  },
  include: ["requireLib"],
  name: "Main",
  out: "bin/Main-built.js",
  optimize: "none",
  wrapShim: true
})

When I run the Optimizer, using Rhino, it builds my output file. In the Main-built.js file, the code for the plugin will come before the required library. This causes an L undefined error.

How do I get the Optimizer to respect the dependency order of my Shims, in order to properly order the library files in my Optimized JS file?

Patrick D
  • 6,659
  • 3
  • 43
  • 55
  • possible duplicate of [requireJS sequential execution for non-AMD js files](http://stackoverflow.com/questions/17914786/requirejs-sequential-execution-for-non-amd-js-files) – Paul Sweatte Dec 26 '14 at 06:28
  • This is bit late, but If you have not solved this problem already, you need to use the shim inside your r.js config as well. that should fix it. – Vishwanath Jan 16 '15 at 11:36

1 Answers1

1

I had a similar problem a while back with knockout extensions and shim didn't work correctly. This is how we solved it.

Create a module called: leafletLib

define(["libs/leaflet","libs/leadleft-dvf"],function(leftlet,dvf){

    return leaflet;
});

LeafletLib has the main library and all of the extensions. On modules that have leaflet or leaflet-dvf as a dependancy you call leafletLib. It is kind of hacky but it might work for you.

define(["leafletLib"],function(leafletLib){});
GrayTower
  • 61
  • 3