2014-10-30 162 views
0

我使用requirejs爲瀏覽器和nodejs編寫了模塊。只在瀏覽器中加載requirejs模塊,而不是在nodejs中加載模塊

一切工作正常,但我想包括一個模塊僅用於瀏覽器,而不是節點,因爲我不需要它,它不會在節點中工作。 (這只是瀏覽器的一個奇特的設計庫)。

我的代碼如下所示:

define([ 
    'requirement', 
    'libs/fancy' 
], function(Requirement, fancy) { 
    // do stuff 
}); 

看中的是,我不希望在節點的lib。所以我可以寫這樣的解決方法:

if (typeof window !== 'undefined') { // cheap detection of browser/node 
    define([ 
     'requirement', 
     'libs/fancy' 
    ], start); 
} else { 
    define([ 
     'requirement' 
    ], start); 
} 

function start(Requirement, Fancy) { 
    // do stuff 
} 

但顯然這是醜陋的。有誰知道更好的方法來做到這一點?

- 編輯1:

var requirements = ['requirement']; 

if (typeof window !== 'undefined') { 
    requirement.push('libs/fancy'); 
} 

define(requirements, function(Requirement, Fancy) { 
    // do stuff 
} 

還不夠完善

回答

1

我有時用你展示創建我把這取決於我需要哪些依賴數組的第二種方法。

但是,有另一種方法,但我不想修改依賴關係列表時使用了。推測模塊內部的代碼必須使用undefined的值Fancy。所以你可以使用下面的內容。這個想法是配置RequireJS加載一個模塊,該模塊在加載時返回undefined值。這樣你就不需要修改你的依賴列表。它只需要能夠處理Fancy未定義的情況。

var requirejs = require("requirejs"); 

// Create a fake module that we name immediately as "undefined". 
requirejs.define("undefined", [], function() { return undefined; }); 

var req = requirejs.config({ 
    map: { 
     // Make it so that all requests for `foo` load `undefined` instead. 
     "*": { 
      foo: "undefined" 
     } 
    } 
}); 

req(["foo"], function (foo) { 
    console.log(foo); 
}); 

上面的示例映射到fooundefined所以當console.log執行時,在控制檯上的值是undefined。在你自己的代碼中,你可以將libs/fancy映射到undefined

此方法的一個變體是使undefined模塊返回一個對象,該對象顯示與真實庫相同的接口但什麼也不做。這將避免必須測試Fancy是否定義在您的模塊內部。雖然我會打電話給僞造的模塊,但不是undefined。也許像fake-fancy