【问题标题】:r.js build fails when trying to evaluate a plugin that shouldn't be evaluated尝试评估不应评估的插件时,r.js 构建失败
【发布时间】:2017-11-22 19:04:25
【问题描述】:

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

导入samples/template/MapLoader! 时,这将返回模块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);
});

我错过了什么?

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

【问题讨论】:

    标签: javascript node.js requirejs amd r.js


    【解决方案1】:

    在 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 模块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 2016-06-12
      • 2020-04-21
      • 1970-01-01
      相关资源
      最近更新 更多