【问题标题】:How can I prevent the Require.js optimizer from including the text plugin in optimized files?如何防止 Require.js 优化器在优化文件中包含文本插件?
【发布时间】:2012-04-29 03:09:51
【问题描述】:

tl;dr:当我的所有文本依赖项都内联时,如何将 text.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 并不多,但我正在努力保持我的代码高度优化,据我了解,如果我的文本依赖项是内联的,则根本不需要文本插件的代码。我可以通过将exclude=text 添加到我的r.js 调用中来保留文本插件,但是如果这样做,当我尝试在浏览器中使用优化代码时出现错误,提示无法加载 text.js 插件.

所以:

  1. text.js 插件在此处实际需要有什么原因吗?

  2. 如果没有,是否有r.js配置选项可以解决此问题,或者

  3. 是否有我可以包含的 text.js 插件的 easy shim 来说服 Require.js 加载了不必要的插件?

【问题讨论】:

    标签: javascript optimization requirejs


    【解决方案1】:

    文本插件确实是必需的,因为 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 选项,请查看 example.build.js 文件。

    【讨论】:

    • 好的,谢谢 - 我会试试这个。基本上答案是(3)制作一个垫片,我可以在我的构建过程中解决这个问题。
    • 为了后代 - 我做了一个这样的垫片:define("text",{load:function(){}}); 并将其附加到我优化文件的开头。似乎工作正常
    • 想知道同样的事情。 stubModules: ['text'] 在新版本的 RequireJS 中发挥作用。
    • 对我不起作用:Error: ENOENT, no such file or directory
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2014-03-05
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多