簡體   English   中英

如何阻止Require.js優化器在優化文件中包含文本插件?

[英]How can I prevent the Require.js optimizer from including the text plugin in optimized files?

tl; dr:當我的所有文本依賴項都被內聯時,如何將text.js插件保留在優化文件之外?

我正在使用Require.js優化器 (通過Node)來優化項目中的一些JS文件。 我正在使用文本插件來加載文本依賴項(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. 是否有一個簡單的shim為text.js插件,我可以包括說服Require.js加載不必要的插件?

文本插件確實是必需的,因為在檢索正確的模塊ID之前,RequireJS需要檢查插件是否實現了方法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選項,請檢查example.build.js文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM