2012-04-17 147 views
20

tl; dr:當我的所有文本依賴關係都內聯時,如何將text.js插件保留在優化文件之外?如何防止Require.js優化器在優化文件中包含文本插件?

我正在使用Require.js optimizer(通過節點)來優化我的項目中的一些JS文件。我正在使用text plugin加載文本依賴關係(HTML模板,CSS)。我有一個模塊,我想優化,包括它的依賴,就像這樣:

define(['text!core/core.css'], function(styles) { 
    // do setup stuff, return an object 
}); 

的Require.js文檔說,當我運行r.js優化,其中我調用core/core.css文件將被內聯像這樣:

$ r.js -o baseUrl=./src name=core out=release/test.js 

Tracing dependencies for: core 
Uglifying file: c:/path/release/test.js 

c:/path/release/test.js 
---------------- 
c:/path/src/text.js 
text!core/core.css 
c:/path/src/core.js 

好消息是,這是有效的。當我看着優化的文件,我可以看到內聯文本,這樣的事情:

define("text!core/core.css",[],function(){return"some CSS text"}), 
define("core",["text!core/core.css"],function(a){ ... }) 

壞消息是,也包括在text.js插件 - 它增加了3K左右,和由(如據我所知)現在完全不需要加載外部文本文件的代碼。我知道3K並不多,但我試圖保持我的代碼高度優化,並且據我所知,如果我的文本依賴關係是內聯的,那麼文本插件的代碼根本就沒有必要。我可以通過在我的r.js調用中添加exclude=text來保留文本插件,但如果我這樣做,當我嘗試在瀏覽器中使用優化的代碼時說我無法加載text.js插件時出現錯誤。

所以:

  1. 沒有任何理由的text.js插件實際需要在這裏?

  2. 如果沒有,是否有r.js,可以解決這個問題,或者

  3. 一個配置選項是否有容易墊片爲text.js插件,我可以包括說服要求。 js,不必要的插件被加載?

回答

15

文本插件真正需要的,因爲RequireJS需要檢查插件實現獲取適當的模塊ID之前的方法normalize

從構建刪除文本插件的方式是使用onBuildWrite設置來創建一個空的插件模塊,在這個問題上的評論描述:https://github.com/jrburke/r.js/issues/116#issuecomment-4185237 - 此功能應該r.js未來版本的土地

編輯:

r.js現在有一個設置稱爲stubModules這正是這麼做的:

//Specify modules to stub out in the optimized file. The optimizer will 
//use the source version of these modules for dependency tracing and for 
//plugin use, but when writing the text into an optimized layer, these 
//modules will get the following text instead: 
//If the module is used as a plugin: 
// define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}}); 
//If just a plain module: 
// define({}); 
//This is useful particularly for plugins that inline all their resources 
//and use the default module resolution behavior (do *not* implement the 
//normalize() method). In those cases, an AMD loader just needs to know 
//that the module has a definition. These small stubs can be used instead of 
//including the full source for a plugin. 
stubModules : ['text'] 

更多r.js運tions檢查example.build.js文件。

+0

好的,謝謝 - 我會試試看。本質上,答案是(3)做一個墊片,我可以在我的構建過程中制定出墊片。 – nrabinowitz 2012-04-18 21:43:45

+1

對於後人 - 我做了一個像這樣的墊片:'define(「text」,{load:function(){}});'並將其附加到我的優化文件的開頭。似乎工作正常 – nrabinowitz 2012-04-20 01:14:18

+1

想知道同樣的事情。 'stubModules:['text']'在更新版本的RequireJS中做到了這一點。 – superlukas 2012-10-12 00:29:45