存在RequireJS时如何防止捆绑的库受到AMD行为的影响

问题描述

我有一个JavaScript包,该包通过HTTP加载到客户端页面中,该页面使用RequireJS加载其依赖项。我使用WebPack编译我的JavaScript包,其中包括许多npm JS包,例如lodash。这些被捆绑到我的包裹中(使用npm)。我的捆绑包还需要通过HTTP动态加载第三方JS库,方法是在客户端页面中注入一个代码块。此图显示了运动部件:

architecture

第三方库也捆绑了自己的模块。我碰巧知道它使用browserify来做到这一点。

我的问题是,各种npm软件包(如lodash)在其发布的代码中都具有如下所示的AMD代码

  // Some AMD build optimizers like r.js check for condition patterns like the following:
  if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
    // Expose lodash to the global object when an AMD loader is present to avoid
    // errors in cases where lodash is loaded by a script tag and not intended
    // as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
    // more details.
    root._ = _;

    // Define as an anonymous module so,through path mapping,it can be
    // referenced as the "underscore" module.
    define(function() {
      return _;
    });
  }

结果是,当我的JS捆绑包运行时,lodash试图变得全局,从而干扰了客户端HTML页面(下划线)中的global _变量。我完全失去了使用WebPack捆绑lodash的好处。我已经通过创建自定义的非AMD构建的lodash并将其源代码作为模块检查到我的捆绑软件中来解决此问题,而不是使用npm。

但是,这种方法不适用于第三方JS库,我需要将其直接动态加载到页面中。该库的与AMD兼容的 的npm模块的行为也有所不同,因为RequireJS位于页面上。

我认为必须有某种方法可以解决此问题,大概是在RequireJS级别。

到目前为止,我已经尝试过:

A)在RequireJS配置中为捆绑包和第三方库使用垫片:

requirejs.config({
  shim: {
    'myBundle': {  exports: 'myBundle' },'my3rdPartyLibrary': {exports: 'my3rdPartyLibrary'}
  },paths: {
    'myBundle': 'http://example.org/myBundle.js','my3rdPartyLibrary': 'http://example.net/library.js'
  }
});

B)通过RequireJS传递lodash:

requirejs.config({
  paths: {
    'lodash': 'https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js'
  },map: {
    'http://example.org/myBundle.js': {
      'underscore': 'lodash'
    },'http://example.net/library.js': {
      'underscore': 'lodash'
    }
  }
});

(这不能解决其他包含AMD代码的模块的问题。)

C)如上所述,自定义lodash构建。这在我的捆绑软件中有效,但不适用于第三方库。

如果在构建时有某种解决方案告诉WebPack(和browserify)在捆绑的模块中剥离所有AMD特定的行为,那可能会起作用。尽管第三方库不是我的,但我可以与供应商合作更新其构建。

解决方法

我有一个类似的问题,我做了一点修改:

define.amd = false;

为什么要这样?因为大多数正在寻找RequireJS的工厂函数都在做:

if (define && define.amd) {
    // define as AMD module
}

这就是骗人的作风,欺骗了第三方