2

我在一个有点特殊的 JS 环境中使用 requirejs,其中应用程序提供了一个全局单例(我无法改变这个事实,这不是在典型的浏览器环境中运行的)。我正在为这个应用程序编写一种 JS SDK,并希望提供使用这个全局的各种模块。

我可以以某种方式将该全局包装在模块中以便从我的模块中要求它吗?就像是

define([the_global_application], function(app)

感谢您对此的想法。

4

1 回答 1

1

是的,你只需要定义它。

// mysingletonapp.js
// define the module for our global var
define(['list', 'any', 'dependency', 'here'], function (l, a, d, h) {
  return yourGlobalVariable;
});

(我不认为你会有依赖项,因为你只是在包装一个 global var

您可以像往常一样使用该模块:

require(['mysingletonapp'], function (app) {
  // do something cool
});

如果你想跳过这一切,你可以使用shimRequireJS 的属性。您只需将其添加到您的选项文件中:

...
shim: {
        'globalApplication': {
            deps: ['underscore', 'jquery'], // again, you should not need them
            exports: 'yourGlobalVar'
        }
}
...

shims 包装不支持 AMD 的库,因此要使此设置正常工作,您需要一个用于globalApplication. 这不是你的情况。

于 2013-03-26T08:07:41.307 回答