nra*_*itz 20 javascript optimization requirejs
tl; dr:当我的所有文本依赖项都被内联时,如何将text.js插件保留在优化文件之外?
我正在使用Require.js优化器(通过Node)来优化项目中的一些JS文件.我正在使用文本插件来加载文本依赖项(HTML模板,CSS).我有一个我想要优化的模块,包括它的依赖项,如下所示:
define(['text!core/core.css'], function(styles) {
// do setup stuff, return an object
});
Run Code Online (Sandbox Code Playgroud)
Require.js文档说core/core.css
我运行r.js
优化器时会内联文件,我正在这样调用:
$ 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
Run Code Online (Sandbox Code Playgroud)
好消息是,这很有效.当我查看优化文件时,我可以看到内联文本,如下所示:
define("text!core/core.css",[],function(){return"some CSS text"}),
define("core",["text!core/core.css"],function(a){ ... })
Run Code Online (Sandbox Code Playgroud)
坏消息是,text.js插件也包含在内 - 它增加了大约3K,并且包含(据我所知)现在完全不必要的代码来加载外部文本文件.我知道3K并不多,但我正在努力保持我的代码高度优化,据我所知,如果我的文本依赖项被内联,那么文本插件的代码根本不是必需的.我可以通过添加exclude=text
到我的r.js
调用来保持文本插件,但如果我这样做,当我尝试在浏览器中使用优化代码时,我会收到错误,说明无法加载text.js插件.
所以:
有没有理由在这里实际需要 text.js插件?
如果没有,是否有一个配置选项的r.js
,可以解决此行为,或
是否有一个简单的shim为text.js插件,我可以包括说服Require.js加载不必要的插件?
Mil*_*ros 15
文本插件确实是必需的,因为normalize
在检索正确的模块ID之前,RequireJS需要检查插件是否实现了该方法.
从构建中删除文本插件的方法是使用该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']
Run Code Online (Sandbox Code Playgroud)
有关更多r.js选项,请检查example.build.js文件.