2016-03-01 50 views
0

我的HTML是這樣的:爲什麼基金會似乎垃圾RequireJS模塊?

<!DOCTYPE html> 
<html> 
<head> 
    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script> 
    <script data-main="/static/scripts/main" src="/static/scripts/require.js"></script> 
</head> 
<body></body> 
</html> 

static/scripts/main看起來是這樣的:

requirejs.config({ 
    paths: { 
     "foundation": '/static/scripts/foundation-6/js/foundation.min' 
    } 
});  

require(["foundation", "moduleA"], function(foundation, moduleA) { 
    console.log("main.js loaded dependencies"); 
}); 

而且static/scripts/moduleA.js是:

console.log("ModuleA loaded"); 

define(function() {  
    console.log("inside moduleA callback"); 
    return { 
     Blah: "Blah!" 
    }  
}); 

我可以看到moduleA.js腳本得到由require裝,但它不被視爲一個模塊,我從控制檯看到內部回調從未被執行。在main.jsconsole.log行中的斷點顯示返回的moduleA不是我期望的模塊,而是Interchange(element, options)的實例,而返回的foundation對象是Abide(element, options)的實例。這些似乎是基礎組件,但我不明白他們爲什麼會返回到這裏。

但是,說我再通過改變需要聲明main.js刪除基金會依賴這樣:

require(["moduleA"], function(moduleA) { 
    console.log("main.js loaded dependencies"); 
}); 

運行使一切按預期方式工作 - 我現在看到的「moduleA回調內部」消息控制檯和斷點顯示我的moduleA對象包含一個Blah成員,如預期的那樣。

這是怎麼回事? Foundation如何攔截這個require()調用並返回一些不需要的內容?我應該把基金會納入這個項目有什麼不同的方式?

回答

1

首先你要弄清楚基礎庫是AMD模塊。您應該打開foundation.js並嘗試在開頭找到此代碼:

if (typeof define === 'function' && define['amd']) { 
    // [1] AMD anonymous module 
    define(['exports', 'require'], factory); 
} 

因此,foundation.js不是AMD模塊。對於非AMD模塊,RequireJS有shim選項。接下來,您應該檢查哪些變量基礎會返回到全局範圍。在302行你可以看到這段代碼:window.Foundation = Foundation;。全局變量是Foundation。結果代碼應該是:

requirejs.config({ 
    paths: { 
     "foundation": 'https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.0/foundation',  
    }, 
    shim:{ 
     "foundation":{ 
      exports:"Foundation" 
     } 
    } 
}); 

但不幸的是,對於foundation.js是不夠的。在303行你可以看到,foundation.js是jquery插件。所以你應該通過RequireJS包含jquery。 jQuery是AMD模塊。你可以在文件中看到它。您應該在shim中包含jQuery作爲foundation.js的依賴項。所以導致代碼將是:

main.js:

requirejs.config({ 
    paths: { 
     "foundation": 'https://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.0/foundation', 
     "jquery":  "https://code.jquery.com/jquery-2.2.1" 
    }, 
    shim:{ 
     "foundation":{ 
      deps: ['jquery'], 
      exports:"Foundation" 
     } 
    } 
}); 

require(["foundation", "moduleA"], function(foundation,moduleA) { 
    debugger; 
    console.log("main.js loaded dependencies"); 
}); 

的index.html:

<html> 
    <head> 
     <script data-main="main.js" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"> </script> 
    </head> 
    <body> 
    </body> 
</html> 

moduleA.js是一樣的。

ps:如果您修復我的語法錯誤,我將不勝感激。

+0

是的,我想就是這樣。在某些時候,我認爲我讀過基金會可能只是需要這種方式,源代碼確實提到了AMD的頂部,但顯然它不能,並且不知何故它設法踐踏整個模塊系統。我會稍微再打開一下,看看有沒有人回答這個問題。 – Kylotan

相關問題