如何在其他任务中从 grunt-prompt 访问用户输入

How do I access a user input from grunt-prompt in other tasks

我需要编写一个 grunt 作业来使用 grunt-prompt 读取用户输入,然后创建一个具有该名称的目录。我正在尝试使用配置访问另一个 grunt 任务中的变量,该任务将在 grunt-prompt 之后执行。但是以下所有方法都给出了 undefined.

我试过了:

grunt.config('config.database')
grunt.config('database')
grunt.config('target.config.database')

请指教。这是我的完整脚本:

module.exports = function(grunt) {

grunt.initConfig({          

    prompt: {
        target: {
            options: {
                questions: [
                    {
                        config: 'directory',
                        type: 'input',
                        message: 'Enter direcotry Name',
                        validate: function(value){
                            if(value == '') {
                                return 'Should not be blank';
                            }
                            return true;
                        }
                    }                       
                ]
            }
        },
    },

    mkdir: {
        all: {
            options: {
                mode: 0777,
                create: [
                    grunt.config('config.directory')
                ]
            }
        }
    }       

});

grunt.loadNpmTasks('grunt-mkdir');
grunt.loadNpmTasks('grunt-prompt');

grunt.registerTask('default', 'prompt:target', 'mkdir']);
};

配置键是directory

但是您的问题是您对 grunt.config() 的调用是在读取 G运行t 文件时执行的,远远早于任务 运行。此时,prompt 还没有 运行,因此该选项未定义。

您想要仅在 运行 时计算的内容,因此请使用模板字符串 '<%= directory %>' 而不是 grunt.config('directory')

mkdir: {
    all: {
        options: {
            mode: 0777,
            create: ['<%= directory %>']
        }
    }
}

只是为了添加一个替代解决方案。在其他情况下可能有用的一个。提示完成后,您可以使用 grunt-prompt 的 then() 来设置配置。

grunt.initConfig({          

prompt: {
    target: {
        options: {
            questions: [
                {
                    config: 'directory',
                    type: 'input',
                    message: 'Enter direcotry Name',
                    validate: function(value){
                        if(value == '') {
                            return 'Should not be blank';
                        }
                        return true;
                    }
                }                       
            ],
            then: function(results){                
                grunt.config.set('mkdir.all.options.create', [results.directory]);                      
            }
        }
    },
},

mkdir: {
    all: {
        options: {
            mode: 0777,
            create: []
        }
    }
}       

});

显然对于示例来说,接受的答案是最干净的解决方案。但是,如果您必须在提示后执行其他任务以及设置配置,则使用 then 函数会很好。