Run a command after a grunt task finishes?

别来无恙 提交于 2019-12-11 09:37:11

问题


I want to run a command but after a task finishes in grunt.

uglify: {
    compile: {
        options: {...},
        files: {...}
    }
    ?onFinish?: {
        cmd: 'echo done!',
        // or even just a console.log
        run: function(){
            console.log('done!');
        }
    }
},

Either run a command in shell, or even just be able to console.log. Is this possible?


回答1:


Grunt does not support before and after callbacks, but next version could implement events that would work in the same way, as discussed in issue #542.

For now, you should go the task composition way, this is, create tasks for those before and after actions, and group them with a new name:

grunt.registerTask('newuglify', ['before:uglify', 'uglify', 'after:uglify']);

Then remember to run newuglify instead of uglify.

Another option is not to group them but remember to add the before and after tasks individually to a queue containing uglify:

grunt.registerTask('default', ['randomtask1', 'before:uglify', 'uglify', 'after:uglify', 'randomtask2']);

For running commands you can use plugins like grunt-exec or grunt-shell.

If you only want to print something, try grunt.log.




回答2:


The grunt has one of the horrible code that I've ever seen. I don't know why it is popular. I would never use it even as a joke. This is not related to "legacy code" problem. It is defected by design from the beginning.

var old_runTaskFn = grunt.task.runTaskFn;

grunt.task.runTaskFn = function(context, fn, done, asyncDone) {
    var callback;
    var promise = new Promise(function(resolve, reject) {
        callback = function (err, success) {
            if (success) {
                resolve();
            } else {
                reject(err);
            }
            return done.apply(this, arguments);
        };
    });

    something.trigger("new task", context.name, context.nameArgs, promise);

    return old_runTaskFn.call(this, context, fn, callback, asyncDone);
}

You can use callback + function instead of promise + trigger. This function will request the new callback wrapper for new task.



来源:https://stackoverflow.com/questions/27182581/run-a-command-after-a-grunt-task-finishes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!