我最近开始学习如何使用GruntJS和Bower。我的任务是使用bower的程序化api和一项艰巨的任务。我想要完成的是调用bower.commands.info来比较所需项目的bower.json中的文件路径和我想要它的本地文件路径。然后应该将所述项目安装到本地路径中。到目前为止它只调用bower.commands.info,但忘记了bower.commands.install。我甚至交换了调用它们的顺序,看它是否会影响任何东西。它只显示信息,但没有安装。希望我的代码能解释更多:
module.exports = function(grunt){
grunt.initConfig({
//this is where the grunt tasks go
//this is where the package info is read in
pkg: grunt.file.readJSON('package.json'), //use comma if adding npm tasks
'bower-install': {
target: {
//point to the html file that is to be updated
html: 'index.html',
//Optional:
//ignorePath: 'wxProj/',
//customize how stylesheets are included
cssPattern: '<link rel="stylesheet" href="{{filePath}}"/>',
//customize how scripts are included
jsPattern: '<script type="text/javascript" src="{{filePath}}"> </script>'
}
}
});
//feel free to load any npm tasks here
grunt.loadNpmTasks('grunt-bower-install');
//this function uses bower to pull some files from my github
grunt.registerTask('extract', function(name){
var bower = require('bower'),
bower_done = this.async(),
wxdesk_contents = '{\n' +
'"directory" : "wxdesk/bower_components"\n' +
'}',
vendor_contents = '{\n' +
'"directory" : "vendor/bower_components"\n'+
'}';
bower.commands.info(name, 'dest')
.on('error', function(){
bower_done(false);
})
.on('end', function(dest){
bower_done();
grunt.log.writeln(dest);
if(dest == 'wxdesk'){
grunt.log.writeln('written to wxdesk!');
//change .bowerrc's "directory" property
grunt.file.write('.bowerrc', wxdesk_contents);
}
else
{
grunt.log.writeln('written to vendor!');
grunt.file.write('.bowerrc', vendor_contents);
}
});
bower.commands.install([name], {save: true})
.on('log', function(result){
grunt.log.writeln(['bower', result.id.cyan, result.message].join(' '));
})
.on('error', function(){
bower_done(false);
})
.on('end', function(results){
bower_done();
//run grunt bower-install
grunt.task.run('bower-install');
});
});
}
答案 0 :(得分:2)
所以我发现了问题,除了睡眠不足。我打电话给bower_done();在bower.commands.info中,它应该只在安装中完成任务线程。 换句话说:
bower.commands.info(name, 'dest')
.on('error', function(){
bower_done(false);
})
.on('end', function(dest){
////////////////////////////////////////////////
//bower_done(); <= This guy should not be here!
////////////////////////////////////////////////
grunt.log.writeln(dest);
if(dest == 'wxdesk'){
grunt.log.writeln('written to wxdesk!');
//change .bowerrc's "directory" property
grunt.file.write('.bowerrc', wxdesk_contents);
}
else
{
grunt.log.writeln('written to vendor!');
grunt.file.write('.bowerrc', vendor_contents);
}
});
bower.commands.install([name], {save: true})
.on('log', function(result){
grunt.log.writeln(['bower', result.id.cyan, result.message].join(' '));
})
.on('error', function(){
bower_done(false);
})
.on('end', function(results){
///////////////////////////////
bower_done(); //<= should be here on the final task to end the async
///////////////////////////////
//run grunt bower-install
grunt.task.run('bower-install');
});