用grunt-cmd-xxx构建seajs项目时,使用alias引发的BUG

该BUG与另一个BUG强相关,见:grunt-cmd-transport提取deps[]的BUG

文件

// employee/static/adder.js

define(function (require, exports) {
    exports.add = function (a, b) {
        return a + b;
    }
});

// employee/static/package.js

define(function (require, exports) {
    exports.adder = require("adder");
});

// bootstrap/static/main.js

define(function (require) {
  var adder = require("employee/static/package").adder;
  alert(adder.add(1, 2));
});

transport: {
            options: {
                paths: [sourceDir],
                alias: {
                    "adder": "employee/static/adder"
                }
            },
            build: {
                files: [
                    {
                        cwd: sourceDir,
                        src: ['**/static/**/*.js', '!3rd-lib/*', '**/static/**/*.css'],
                        dest: buildDir
                    }
                ]
            }
        }

BUG描述

执行grunt transport,main.js提取之后:

define("bootstrap/static/main", [ "employee/static/package", "adder" ], function(require) {
  var adder = require("employee/static/package").adder;
  alert(adder.add(1, 2));
});

package.js提取后是:

// employee/static/package.js
define("employee/static/package", [ "employee/static/adder" ], function(require, exports) {
    exports.adder = require("employee/static/adder");
});

可以看到,package.js提取结果是正确的,而且alias也正确转换。但是受上一个BUG的影响,main.js的提取结果是错误的,不仅把adder也写入了deps[],而且没有alias转换成功

在链接的文档里介绍过,规避上一个BUG的方法,是在concat中配置include:all。但是现在由于alias转换失败的原因,执行grunt concat时会报错:

Running "concat:build" (concat) task
>> file adder not found
>> file adder-debug not found

然后合并得到的main.js是:

// concated bootstrap/static/main.js
define("bootstrap/static/main", [ "employee/static/package", "adder" ], function(require) {
    var adder = require("employee/static/package").adder;
    alert(adder.add(1, 2));
});

define("employee/static/package", [ "employee/static/adder" ], function(require, exports) {
    exports.adder = require("employee/static/adder");
});

package.js:

// employee/static/package.js
define("employee/static/package", [ "employee/static/adder" ], function(require, exports) {
    exports.adder = require("employee/static/adder");
});

define("employee/static/adder", [], function(require, exports) {
    exports.add = function(a, b) {
        return a + b;
    };
});

结果比无效的http请求更严重,因为合并后的main.js已经包含了package,所以不会去请求employee/static/package.js,但是main中并没有adder存在,所以根本调不到adder。同时会发起2个无效的http请求,尝试加载adder.js和employee/static/adder.js

用grunt-cmd-xxx构建seajs项目时,使用alias引发的BUG_第1张图片

结论

在BUG修复之前:

  • 如果使用grunt-cmd-transport和grunt-cmd-concat来构建seajs项目,不要使用alias,使用完整的顶级标识,或者相对标识都可以
  • concat设置为include:all,来规避无效http请求的问题

你可能感兴趣的:(用grunt-cmd-xxx构建seajs项目时,使用alias引发的BUG)