2013-03-16 112 views
0

我使用的一个项目requirejs和我有2个模块:之前AMD模块添加非AMD模块

  • a.js:是,我不能触摸它的代码的非AMD模块
  • b.js:是我用define()函数编写的AMD模块。它需要a.js才能工作。
  • app.js:是同时使用a.jsb.js的实际应用程序代码。

app.js看起来是这样的:

//source code for app.js 
require(['a.js', 'b.js'], 
function(a, b) { 
    a.x = 2;//this will fail because 'a' is not defined 
}); 

现在的问题是:什么是require()app.js两个模块的最简单的方法?我不能做到这一点,如:

//source code for app.js 
require(['b.js', 'a.js'], 
function(b) { 
    a.x = 2;//it works because module 'a' defines a global variable named 'a' 
    b.x = 2;//this will fail because module 'b' is loaded before 'a' so it doesn't work 
}); 

回答

2

因为,如你所说,a.js出口一个名为a全局变量,可以配置RequireJS使用shim config option揭露它在AMD的方式。任何需要a.js的模块都不会知道它不是一个合适的模块。在你的情况下,配置会是这样的:

requirejs.config({ 
    shim: { 
     'a.js': { 
      exports: 'a' // a.js defines 'window.a' 
     } 
    } 
}); 
0

这是AMD装载机的标准票价。大多数时候,垫片不需要。您的app.js源代码是正确的,但您没有显示b.js的源代码。既然你有过b.js控制,应该写成AMD模块与a.js依赖

// source code for b.js 
// You have to use define, not require, and the dependency on a.js must be here rather than via a nested or internal require 
define(['a.js'], function(a){ 
    // your code for b.js 
}); 

这将确保a.js是b.js之前加载时app.js准备就绪执行。

相关问题