2013-03-16 83 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準備就緒執行。