javascriptnode.jsrequirejsamdr.js

r.js build fails when trying to evaluate a plugin that shouldn't be evaluated


I have an AMD plugin named MapLoader.

When importing samples/template/MapLoader!, this will either return the module luciad/view/Map or the module luciad/view/WebGLMap, depending on the URL query parameter "webgl".

Here's the code of the plugin :

define({
  load: function(na, require, onload, config) {
    if (window.location.search.indexOf('webgl') > 0 && 
        window.location.search.indexOf('webgl=false' < 0)) {
      map = "luciad/view/WebGLMap";
    } else {
      map = "luciad/view/Map";
    }

    require([map], function(value) {
      onload(value);
    });
  }
});

Now, I'm trying to use r.js to pack my project, but it doesn't know how to deal with this module, because it tries to evaluate the code. Hence, it produces the following error :

{ Error: ReferenceError: window is not defined
In module tree:
    samples/balloons/main
      samples/template/sample
        samples/template/MapLoader
  ...
}

My current config looks like this :

require('requirejs').optimize({
  baseUrl : moveFrom,
  modules: [
    { name: "./samples/template/MapLoader" }, 
    { name: "./samples/balloons/main" }
  ],
  packages: [
    { name: "loader", location: "./samples/lib/requirejs" },
    { name: "luciad", location: "./luciad" },
    { name: "samples", location: "./samples" }
  ],
  paths: {
    jquery: "./samples/lib/jquery/jquery-1.12.4"
  },
  dir : moveTo,
  stubModules: ['./samples/template/MapLoader'],
  optimize : "none",
  uglify2 : {
    output: {
      beautify: false
    },
    compress: {},
    warnings: true,
    mangle: true
  }
}, function (buildResponse) {
  console.log(buildResponse);
});

What am I missing?

What is the correct way to add this plugin to my build?


Solution

  • With a little help from RequireJS author James Burke in this Github issue, I came up with the following solution :

    define({
      load: function(na, require, onload, config) {
        var WebGLMap = "luciad/view/WebGLMap";
        var RegularMap = "luciad/view/Map";
        // Require both maps when running the loader in r.js
        // The parameter passed to "onload" is not important here
        if (typeof window === 'undefined') {
          return require([WebGLMap, RegularMap], function() {
            onload();
          });
        }
    
        if (window.location.search.indexOf('webgl') > 0 && 
            window.location.search.indexOf('webgl=false' < 0)) {
          map = WebGLMap;
        } else {
          map = RegularMap;
        }
        require([map], function(value) {
          onload(value);
        });
      }
    });
    

    When typeof window === 'undefined', the code will assume r.js is being used to execute the code and both modules will be required instead of one, correctly packing the WebGLMap and Map modules.