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

How can I call grunt prompt task from copy task?

我正在使用 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,这与我如何调用它有关。

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

这是您可以在 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.

我最终解决了这个差异。我没有检查目录是否存在,而是获取目录列表,将其传递给提示问题并强制用户在执行复制任务之前选择目录。

//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')
            }]
        }
    }
};