将grunt参数从一个任务传递到另一个任务

时间:2014-03-04 01:30:05

标签: asynchronous configuration dependencies gruntjs

我正在尝试将从服务器(zookeeper)返回的配置值传递到指南针(cdnHost,环境等),并且似乎很难使用正确的方法。

我研究了在此页面上将args从一个任务传递到另一个任务的方法

http://gruntjs.com/frequently-asked-questions#how-can-i-share-parameters-across-multiple-tasks

module.exports = function(grunt) {
    grunt.initConfig({
        compass: {
            dist: {
                //options: grunt.option('foo')
                //options: global.bar
                options: grunt.config.get('baz')
            }
        },

    ...

    grunt.registerTask('compassWithConfig', 'Run compass with external async config loaded first', function () {
        var done = this.async();
        someZookeeperConfig( function () {
            // some global.CONFIG object from zookeeper
            var config = CONFIG;
            // try grunt.option
            grunt.option('foo', config);
            // try config setting
            grunt.config.set('bar', config);
            // try global
            global['baz'] = config;
            done(true);
        });
    });

    ...

    grunt.registerTask('default', ['clean', 'compassWithConfig', 'compass']);

我也试过直接调用罗盘任务,但没有区别。

grunt.task.run('compass');

任何见解都将不胜感激。 (例如,使用initConfig并使值可用)。

由于

1 个答案:

答案 0 :(得分:4)

当你写:

grunt.initConfig({
    compass: {
        dist: {
            options: grunt.config.get('baz')
        }
    }
立即调用

... grunt.config,并返回baz的值,因为它现在是 。在另一个任务中改变它(稍后)根本不会被提起。

如何解决?

#1:更新compass.dist.options而不是更新baz

grunt.registerTask('compassWithConfig', 'Run compass with external async config loaded first', function () {
    var done = this.async();
    someZookeeperConfig( function () {
        // some global.CONFIG object from zookeeper
        var config = CONFIG;
        grunt.config.set('compass.dist.options', config);
        done();
    });
});

现在,首先运行任务compassWithConfig,然后任务compass将获得您期望的结果。

#2:总结罗盘任务执行以抽象出配置映射

grunt.registerTask('wrappedCompass', '', function () {
    grunt.config.set('compass.dist.options', grunt.config.get('baz'));
    grunt.task.run('compass');
});

// Then, you can manipulate 'baz' without knowing how it needs to be mapped for compass

grunt.registerTask('globalConfigurator', '', function () {
    var done = this.async();
    someZookeeperConfig( function () {
        // some global.CONFIG object from zookeeper
        var config = CONFIG;
        grunt.config.set('baz', config);
        done();
    });
});

最后,运行任务globalConfigurator然后wrappedCompass会让您获得结果。

相关问题