如何使用Grunt和Grunt-Watch基于子文件夹执行任务

时间:2015-03-30 14:22:09

标签: gruntjs grunt-contrib-watch

我希望能够在我的主项目中拥有不同的子项目。例如:

-- my-project/
   - Gruntfile.js
   - subproject1/
     - index.html
     - scss/
       - main.scss
   - subproject2/
     - index.html
     - scss/
       - main.scss

我希望能够在不触发子项目2任务的情况下修改子项目1中的文件。

截至目前,我正在配置我的gruntfile,如下所示:

watch: {
    subproject1: {
        files: ['subproject1/*.html', 'subproject1/scss/**/*.scss'],
        tasks: ['sass', 'premailer:subproject1']
    },
    subproject2: {
        files: ['subproject2/*.html', 'subproject2/scss/**/*.scss'],
        tasks: ['sass', 'premailer:subproject2']
    }
},

premailer: {
    subproject1: {
        options: {
            css: 'subproject1/css/main.css',
            verbose: false
        },
        files: [
            {
            'subproject1/dist/index.html' : 'subproject1/index.html'
            }
        ]
    },
    subproject2: {
        options: {
            css: 'subproject2/css/main.css',
            verbose: false
        },
        files: [
            {
            'subproject2/dist/index.html' : 'subproject2/index.html'
            }
        ]
    },
}

有没有办法根据修改的文件动态指定grunt要运行的任务(例如,我修改文件夹 /index.html,然后运行premailer:文件夹 )或者这是实现它的唯一方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用grunt.file方法(docs here)检查Gruntfile中主文件夹中的所有文件夹,创建子项目名称数组,然后使用forEach动态创建任务。

这样的事情应该去:

/*global module:false*/
module.exports = function(grunt) {

    var mycwd = "./";

    var tempFileList = grunt.file.expand(
        { filter: function (src) {
            if (grunt.file.isDir(src) == true) {
                return true;
            }
            return false;
        } },
        [ mycwd + "!(Gruntfile.js|node_modules|package.json)" ] // structure to analyse
    );

    // I create an empty array to put all elements in, once cleaned.
    var fileList = [];

    tempFileList.forEach(function(url){
        var cwd = url;
        cwd = cwd.replace(mycwd, "");
        fileList.push(cwd);
    })

    var watchObject = {};
    var premailerObject = {};

    fileList.forEach(function(name) {
        watchObject[name] = {
            files: [name + '/*.html', name + '/scss/**/*.scss'],
            tasks: ['sass', 'premailer:' + name]
        };
        var filesObject = {};
        filesObject[name+'/css/main.css'] = name + '/index.html';
        premailerObject[name] = {
            options: { css: name + '/css/main.css', verbose: false },
            files: [ filesObject ]
        };
    });

    var configObject = {
        watch: watchObject,
        premailer: premailerObject
    };

    // just to check the final structure
    console.log(configObject); 

    grunt.initConfig(configObject);

};