2012-04-17 150 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