简体   繁体   English

如何不与requireJS的require / define方法冲突?

[英]How do I noConflict the requireJS require/define methods?

Looking for requirejs.noConflict() , or some way to remove the global footprint from the library. 寻找requirejs.noConflict()或以某种方式从库中删除全局足迹。 My use case is that I'm writing a widget to run in a 3rd party page which might already define require and define (with a previous version of requirejs or even another library entirely). 我的用例是,我正在编写一个小部件以在第3方页面中运行,该小部件可能已经定义了requiredefine (使用早期版本的requirejs或完全是另一个库)。

I've tried implementing this myself and it mostly works. 我已经尝试过自己实现,并且大多数情况下都可以。 For simplicity lets assume I do not restore original values, only remove the footprint. 为简单起见,假设我不还原原始值,仅删除覆盖区。 I do something like this in my data-main: 我在数据主数据库中执行以下操作:

  var mycontext = requirejs.config({context : 'asdf', baseUrl : 'http://foo.com' });

  mycontext(['require','foo'], function (require, foo) {
        var f = require('foo');
  });

  // namespace cleanup
  window.requirejs = undefined;
  window.require = undefined;
  window.define = undefined;

The problem here is that the f value from require('foo') returns null, but only iff I do my namespace cleanup. 这里的问题是来自require('foo')f值返回null,但仅当我执行命名空间清理时才如此。 This smells like a bug in requirejs, but I'm hoping there's an official no-conflict solution. 这闻起来就像requirejs中的错误,但我希望有一个官方的无冲突解决方案。

Hard to google this one due to all the jQuery related noConflict() questions. 由于所有与jQuery相关的noConflict()问题,很难用谷歌搜索这个。

The RequireJS documentation has a section on this titled " HOW CAN I PROVIDE A LIBRARY TO OTHERS THAT DOES NOT DEPEND ON REQUIREJS? " RequireJS文档中的标题为“ 我如何向不依赖REQUIREJS的其他人提供一个库? ”的一节。

You can also have a look at the example build file , which shows how wrap can be used. 您还可以查看示例构建文件 ,该文件显示了如何使用wrap

A good example of how this works is the Flight library . 飞行库就是一个很好的例子。

By default the library uses AMD but there is a standalone version that wraps all the modules in an anonymous function and includes a tiny require/define API at the top (They use their own build tool for this). 默认情况下,该库使用AMD,但有一个独立版本,该版本将所有模块包装为匿名函数,并在顶部包含一个微小的require / define API(为此,他们使用自己的构建工具 )。 Source can be found here . 来源可以在这里找到。

Note that for this to work all the modules will require IDs, but the r.js optimiser will handle that for you. 请注意,要使此模块正常运行,所有模块都将需要ID,但是r.js优化器将为您处理该ID。

Using these techniques should allow you to leave any already defined require/define variables alone. 使用这些技术应该可以让您不留任何已定义的需求/定义变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM