如何在grunt.initConfig()之前执行asynchronous操作?

现在我有我的Gruntfile设置来执行一些自动检测魔术,如parsing源文件来parsingroder中的一些PHP源,以dynamic地找出运行grunt.initConfig()之前我需要知道的文件名和path。

不幸的是, grunt.initConfig()似乎并不是要asynchronous运行,所以我没有办法让我的asynchronous代码执行之前,我可以调用它。 有没有一个技巧来完成这个或我必须重写我的检测程序同步? 在我的callback到达之前有没有简单的方法来阻止执行?

内部的grunt任务当然有this.async() ,但是对于initConfig()不起作用。

这是一个简单的例子:

 function findSomeFilesAndPaths(callback) { // async tasks that detect and parse // and execute callback(results) when done } module.exports = function (grunt) { var config = { pkg: grunt.file.readJSON('package.json'), } findSomeFilesAndPaths(function (results) { config.watch = { coffee: { files: results.coffeeDir + "**/*.coffee", tasks: ["coffee"] // ... } }; grunt.initConfig(config); grunt.loadNpmTasks "grunt-contrib-coffee" // grunt.loadNpmTasks(...); }); }; 

任何好的想法如何做到这一点?

非常感谢!

我会把它作为一个任务,因为Grunt是同步或如果你可以使findSomeFilesAndPaths同步。

 grunt.initConfig({ initData: {}, watch: { coffee: { files: ['<%= initData.coffeeDir %>/**/*.coffee'], tasks: ['coffee'], }, }, }); grunt.registerTask('init', function() { var done = this.async(); findSomeFilesAndPaths(function(results) { // Set our initData in our config grunt.config(['initData'], results); done(); }); }); // This is optional but if you want it to // always run the init task first do this grunt.renameTask('watch', 'actualWatch'); grunt.registerTask('watch', ['init', 'actualWatch']); 

解决了重写,同步的风格。 ShellJS派上用场,尤其是对于同步执行的shell命令。

您如何在Grunt中使用ShellJS的示例:

 grunt.initConfig({ paths: { bootstrap: exec('bundle show bootstrap-sass').output.replace(/(\r\n|\n|\r)/gm, '') }, uglify: { vendor: { files: { 'vendor.js': ['<%= paths.bootstrap %>/vendor/assets/javascripts/bootstrap/alert.js'] } } });