4

我正在处理一个非常大的项目,该项目使用:

  1. 包含带有脚本标记的 javascript 文件的旧版 JSP 页面
  2. 使用其他没有 RequireJS 的 javascript 模块的主干模型和视图

我们现在想开始将 RequireJS 与 jQuery、BackboneJS 和 UnderscoreJS 一起用于我们从现在开始开发的所有内容,但是我们没有资源来重写所有遗留 JSP 页面。我们可能有时间重写我们已经开发的 Backbone 模型和视图。

问题在于,对于我们的遗留代码(上面的 1 和 2),我们将所有 javascript 文件包含在一个巨大的文件中并发送到浏览器。这个巨大的文件必须能够与我们的新 RequireJS 模板共存,但是我怎样才能例如分离巨大文件的某些部分,以便我可以将它们与使用 RequireJS 的模板一起使用?无需重写所有使用这部分文件的页面,也无需重复代码。

谢谢!

4

2 回答 2

4

我不知道我是否完全掌握了手头的问题,但我认为 RequireJS 的shimormap函数会帮助你。

从巨大的 javascript 文件中提取新模块中所需的部分。然后告诉 RequireJS,你巨大的 javascript 文件是这个使用 shim 的新模块的依赖项。就像是:

requirejs.config({
    shim: {
        'new-module': {
            deps: ['huge-javascript-file'],
            exports: 'NewModule'
    }
});

垫片文档:http ://requirejs.org/docs/api.html#config-shim

当只有部分新代码必须使用旧的大文件时,map 函数可能很有用。查看此文档:http ://requirejs.org/docs/api.html#config-map

于 2013-01-29T17:03:37.607 回答
2

I don't think there is One True Way to achieve this, but I've approached a similar problem by defining module "facades" around the globally scoped code. Let's say your legacy scripts define a global variable called foo. You can define a AMD module and export that variable from it:

//foo.js
define(function() {
  return window.foo;
});

//bar.js
define(['foo'], function(foo) {
  //do something with foo
});

This way you only need to write a single-line facade every time you need to use a new piece of the existing, globally defined code, without breaking existing code which expects the same code to be globally defined. Over time you can move and refactor the actual implementation into the module without breaking consumer code.

于 2013-01-29T16:46:17.487 回答