我目前正在尝试通过发送参数以多次运行另一个任务的方式创建一个任务。
这是我已经正常运行的单一构建任务:
var country = grunt.option('country') || 'X0';
var product = grunt.option('product') || 'Y0';
var subdomain = grunt.option('subdomain') || 'Z0';
grunt.registerTask('build_home', [
'sprite:publicProduct',
'sprite:home',
'uglify:home',
'sass:home',
'csscomb:home',
'cssmin:home'
]);
因此,在日常工作中,我将运行以下命令:
grunt build_home --country=X0 --product=Y7 --subdomain=Z3
我现在要执行的任务是运行所有可能的预定义选项:
grunt build_home_all
会是这样的:
grunt.registerTask('build_home_all', function() {
var products = ['Y0','Y1','Y2','Y3','Y4','Y5','Y6','Y7','Y8','Y9'];
var subdomains = ['Z0','Z1','Z2'];
for (i = 0; i < products.length; i++) {
for (j = 0; j < subdomains.length; j++) {
grunt.task.run('build_home --product='+products[i]+' --subdomain='+subdomains[j]);
};
};
grunt.log.ok(['Finished.']);
});
我已经用grunt.util.spawn实现了它,但是它有点异步运行,并且迫使我的cpu同时运行各种任务。
当使用grunt.task.run
调用任务的方法时,您将无法像通常使用CLI那样传递参数,但是仍然可以使用冒号分隔的符号传递参数:
build_home --country=X0 --product=Y7 --subdomain=Z3
=>build_home:X0:Y7:Z3
将您的build_home_all
任务更新为以下内容:
function buildHomeAll() = {
var products = ['Y0','Y1','Y2','Y3','Y4','Y5','Y6','Y7','Y8','Y9'],
subdomains = ['Z0','Z1','Z2'],
tasks = [],
country = grunt.option('country') || 'X0';
for (i = 0; i < products.length; i++) {
for (j = 0; j < subdomains.length; j++) {
tasks.push(['build_home',country, products[i],'subdomains[j]'].join(':'));
};
};
grunt.task.run(tasks);
grunt.log.ok(['Finished.']);
}
您将使用调用此函数 grunt build_home_all --country=X0
接下来,您将需要修改build_home
任务以说明可以传入参数的新方式:
function buildHome() = {
if (!grunt.option('country') {
grunt.option('country', this.args[0] || 'X0');
})
if (!grunt.option('product') {
grunt.option('product', this.args[1] || 'Y0');
})
if (!grunt.option('subdomain') {
grunt.option('subdomain', this.args[2] || 'Z0');
})
grunt.task.run([
'sprite:publicProduct',
'sprite:home',
'uglify:home',
'sass:home',
'csscomb:home',
'cssmin:home'
]);
最后,在您的中公开这些功能gruntfile.js
:
grunt.registerTask('build_home', buildHome);
grunt.registerTask('build_home_all', buildHomeAll);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句