0

我已经很好地实现了 RequireJS,并且基于 Grunt 的构建过程通过 r.js 将所有 JS 文件应用程序优化到一个文件中,这也可以正常工作。我所有的应用程序文件都连接到一个大的 JS 文件中,以实现高效的生产部署。现在我有以下要求:我需要为requirejs编写一个插件,它不会在构建过程中加载(不包括文件)到优化文件中,但会按需需要:在我的代码中我会有:

var myObj = require("myplugIn!jsFile");

所以最后当这条线运行时,它将以 2 个选项运行:

  1. 在构建过程中,该文件不包含在优化文件中
  2. 应用程序正在运行,它将按需请求文件。

我编写了以下插件,但无法正常工作:

define(function () {
"use strict";
return {
    load : function (name, req, onload, config) {
        // we go inside here we are running the application not in build process
        if (!config.isBuild) {
            req([name], function () {
                    onload(arguments[0]);
                });                
        } 
    }
};
});

我在这里缺少什么。

4

2 回答 2

2

在您的构建配置中,您可以排除您不想捆绑的文件。它们仍将在需要时按需加载。你也可以这样做:

define(function (){
    // module code...

    if (condition){
        require(['mymodule'], function () {
            // execute when mymodule has loaded.
        });
    }

}):

mymodule只有满足条件时才会加载这种方式。只有一次,如果您在其他地方使用相同的模块依赖项,它将返回加载的模块。

于 2013-06-12T18:36:39.590 回答
0

更简单的是,如果对某人有帮助,我会发布解决方案,我创建一个插件,在构建过程中不返回任何内容,在运行时返回所需的文件,希望对某人有所帮助。

define(function () {
"use strict";

return {
    load : function (name, req, onload, config) {
        if (config.isBuild) {
            onload(null);
        } else {
            req([name], function () {
                onload(arguments[0]);
            });
        }
    }
};

});

于 2013-06-16T05:50:43.670 回答