r.js 尝试评估不应评估的插件时构建失败

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

我有一个名为 MapLoader 的 AMD 插件。

导入 samples/template/MapLoader! 时,这将 return 模块 luciad/view/Map 或模块 luciad/view/WebGLMap,具体取决于 URL 查询参数 "webgl".

插件代码如下:

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);
    });
  }
});

现在,我正在尝试使用 r.js 打包我的项目,但它不知道如何处理这个模块,因为它试图评估代码。因此,它会产生以下错误:

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

我当前的配置如下所示:

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);
});

我错过了什么?

将此插件添加到我的构建中的正确方法是什么?

在 RequireJS 作者 James Burke in this Github issue 的帮助下,我想出了以下解决方案:

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);
    });
  }
});

typeof window === 'undefined' 时,代码将假定 r.js 用于执行代码,并且需要两个模块而不是一个模块,正确打包 WebGLMapMap 模块。