20

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 文档说,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

好消息是,这行得通。当我查看优化后的文件时,我可以看到内联文本,如下所示:

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

坏消息是,text.js 插件也包括在内——它增加了大约 3K,并且由(据我所知)现在完全不需要的用于加载外部文本文件的代码组成。我知道 3K 并不多,但我正在努力使我的代码保持高度优化,据我所知,如果我的文本依赖项是内联的,则根本不需要文本插件的代码。我可以通过添加exclude=text到我的r.js调用中来阻止文本插件,但是如果我这样做了,当我尝试在浏览器中使用优化代码时,我会收到一个错误,提示无法加载 text.js 插件。

所以:

  1. 有什么理由在这里实际上需要text.js 插件吗?

  2. 如果没有,是否有可以修复此行为的配置选项,或者r.js

  3. text.js 插件是否有一个简单的填充程序,我可以包含它来说服 Require.js 加载了不必要的插件?

4

1 回答 1

15

文本插件确实是必需的,因为 RequireJS 需要normalize在检索正确的模块 ID 之前检查插件是否实现了该方法。

从构建中删除文本插件的方法是使用该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文件。

于 2012-04-18T16:23:38.630 回答