如何从复制任务调用grunt提示任务?

时间:2016-01-25 18:54:31

标签: javascript gruntjs grunt-prompt

我正在使用load-grunt-config,我在Gruntfile.js中有一个简单的复制任务设置,

grunt.registerTask('copy-css', 'Blah.', ['copy:css'])

然后在我的copy.js文件中我有这个(忽略无效的代码。复制任务工作正常,我只是设置这个例子。)

'use strict';

module.exports = function(grunt, options) {
    if(!grunt.file.exists(foldername)) { 
        //I NEED TO RUN A PROMPT HERE BUT THIS IS NOT WORKING
        grunt.task.run('prompt:directory-exists');
    }

    return {
        'css': {
            'files': [{
            }]
        }
    };
};

我的提示任务看起来像这样,

'use strict';

module.exports = {
    'directory-exists': {
        'options': {
            'questions': [{
                'type': 'confirm',
                'message': 'That folder already exists. Are you sure you want to continue?',
                'choices': ['Yes (overwrite my project files)', 'No (do nothing)']
            }]
        }
    }
};

Grunt虽然没有找到这个任务,但我认为这与我如何调用它有关,因为我正在使用load-grunt-config。

2 个答案:

答案 0 :(得分:2)

如果您注册任务,您将可以访问grunt配置中的任务(如提示)。

以下是您可以在Gruntfile.js中创建的任务示例:

grunt.registerTask('myowntask', 'My precious, my own task...', function(){
    // init
    var runCopy = true;

    // You'll need to retrieve or define foldername somewhere before...
    if( grunt.file.exists( foldername )) {
        // If your file exists, you call the prompt task, with the specific 'directory-exists' configuration you put in your prompt.js file
        grunt.task.call('prompt:directory-exists');
    }

}

然后,您运行grunt myowntask

答案 1 :(得分:0)

我最终解决了这个不同之处。我只是获取目录列表,将其传递给提示问题并强制用户在进入复制任务之前选择一个目录,而不是检查目录是否存在。

//Get directories
var projects = grunt.file.expand({filter: "isDirectory", cwd: "project"}, ["*"]);

//Format these for grunt-prompt
grunt.option('global.project.list', projects.map(function (proj_name) { return { 'value': proj_name, 'name': proj_name}; }));

//Prompt.js
return {
    //Prompt the user to choose their directory
    'project-name': {
        'options': {
            'questions': [{
                config: 'my.selection', 
                type: 'list',
                message: 'Choose directory to copy to?', 
                choices: grunt.option('global.project.list')
            }]
        }
    }
};