grunt-cmd-transport提取deps[]的BUG

时间:2022-05-01 09:31:56

该BUG已经在GitHub上提了issue,详见:#56

文件

// employee/static/adder.js
define(function (require, exports) {
exports.add = function (a, b) {
return a + b;
}
});
// employee/static/package.js,该文件作为employee模块的唯一出口
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));
});

BUG描述

执行grunt transport之后,提取的bootstrap/static/main.js变成:

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

提取的employee/static/package.js是:

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

可以看到,package.js的提取结果是正确的,但是main.js的deps[]里,多了不应该存在的employee/static/adder,实际上期待的main.js应该是:

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

尝试用spm-build来构建,得到的main.js就是上述期待的结果

这造成的结果是,在seajs.use("bootstrap/static/main")之后,浏览器会请求employee/static/adder.js,但是这个文件实际上不存在

grunt-cmd-transport提取deps[]的BUG

规避方法

最好的办法当然还是grunt-cmd-transport修复这个BUG。在修复之前,可以在concat中将include配置为all,暂时规避此BUG

// Gruntfile.js
concat: {
options: {
paths: [buildDir],
include: 'all'
},
build: {
files: [
{
expand: true,
cwd: buildDir,
src: ['**/package.js', '**/package-debug.js', '**/main.js', '**/main-debug.js'],
dest: finalDir
}
]
}
}

这样虽然transport提取的中间文件的deps[]还是错的,但是concat main.js会把所有的依赖都合并进来:

// bootstrap/static/main.js,这次把所有的依赖都合并进来了
define("bootstrap/static/main", [ "employee/static/package", "employee/static/adder" ], function(require) {
var adder = require("employee/static/package").adder;
alert(adder.add(1, 2));
}); define("employee/static/package", [ "./adder" ], function(require, exports) {
exports.adder = require("./adder");
}); define("employee/static/adder", [], function(require, exports) {
exports.add = function(a, b) {
return a + b;
};
});

再用浏览器访问:

grunt-cmd-transport提取deps[]的BUG

可以看到,因为main.js里面已经全部都有了,所以不会再发起额外的http请求(连employee/static/package.js都不请求)。这个方法可以规避这个BUG,但是seajs异步加载的特性就浪费了,只能期待transport插件尽快修复此BUG