2013-05-14 5 views
20

Итак, на странице информации о плагине grunt-contrib-watch есть пример того, как сделать запуск jshint только для измененного файла.Gruntjs: Как сделать задачу копирования для копирования только измененных файлов на часы

grunt.initConfig({ 
    watch: { 
    scripts: { 
     files: ['lib/*.js'], 
     tasks: ['jshint'], 
     options: { 
     nospawn: true, 
     }, 
    }, 
    }, 
    jshint: { 
    all: ['lib/*.js'], 
    }, 
}); 

grunt.event.on('watch', function(action, filepath) { 
    grunt.config(['jshint', 'all'], filepath); 
}); 

Я не тестировал пример сам. Но взял это и применил к моей задаче копирования, безуспешно. Задача grunt-contrib-copy, созданная для копирования изображений и шаблонов для моего углового проекта. И я был бы рад узнать, смогу ли я сделать эту работу для задачи копирования, и если смогу, что я делаю неправильно.

Большое вам спасибо.

Вот мой лишенный Gruntfile.js.

// Build configurations. 
module.exports = function(grunt){ 

    // Project configuration. 
    grunt.initConfig({ 

     pkg: grunt.file.readJSON('package.json'), 

     // Copies directories and files from one location to another. 
     copy: { 
     // DEVELOPMENT 
     devTmpl: { 
      files: [{ 
      cwd  : 'src/tpl/', 
      src  : ['**/*'], 
      dest : 'app/tpl/', 
      flatten : false, 
      expand : true 
      }] 
     }, 
     devImg: { 
      files: [{ 
      cwd  : 'src/img/', 
      src  : ['**/*'], 
      dest : 'app/img/', 
      flatten : false, 
      expand : true 
      }] 
     } 
     }, 

     // Watch files for changes and run tasks 
     watch: { 
     // Templates, copy 
     templates: { 
      files : 'src/tpl/**/*', 
      tasks : ['copy:devTmpl'], 
      options: { 
      nospawn: true, 
      } 
     }, 
     // Images, copy 
     images: { 
      files : 'src/img/**/*', 
      tasks : ['copy:devImg'], 
      options: { 
      nospawn: true, 
      } 
     } 
     } 

    }); 

    // Watch events 
    grunt.event.on('watch', function(action, filepath) { 
     // configure copy:devTmpl to only run on changed file 
     grunt.config(['copy','devTmpl'], filepath); 
     // configure copy:devImg to only run on changed file 
     grunt.config(['copy','devImg'], filepath); 
    }); 

    // PLUGINS: 
    grunt.loadNpmTasks('grunt-contrib-copy'); 


    // TASKS: 

    /* DEV: Compiles the app with non-optimized build settings, places the build artifacts in the dist directory, and watches for file changes. 
    run: grunt dev */ 
    grunt.registerTask('dev', 'Running "DEVELOPMENT", watching files and compiling...', [ 
     'default', 
     'watch' 
    ]); 

    /* DEFAULT: Compiles the app with non-optimized build settings and places the build artifacts in the dist directory. 
    run: grunt */ 
    grunt.registerTask('default', 'Running "DEFAULT", compiling everything.', [ 
     'copy:devTmpl', 
     'copy:devImg' 
    ]); 

} 
+0

Есть возможность использовать более новую задачу, я думаю. – GnrlBzik

ответ

5

Вы должны указать grunt.config на правильную собственность в вашей конфигурации:

grunt.event.on('watch', function(action, filepath) { 
    var cfgkey = ['copy', 'devTmpl', 'files']; 
    grunt.config.set(cfgkey, grunt.config.get(cfgkey).map(function(file) { 
    file.src = filepath; 
    return file; 
    })); 
}); 
+0

Ожидание ... Фатальная ошибка: Объект 0 не имеет метода «заменить» – GnrlBzik

+0

Кстати, спасибо @ kyle-robinson-young – GnrlBzik

+0

О, моя ошибка, я думал, что вы можете настроить конфигурацию таким образом. Я отредактировал ответ. Попробуйте это вместо этого. –

17

Использование хрюкать-синхронизации (https://npmjs.org/package/grunt-sync) вместо пехотинца-вно-копии, и посмотреть каталоги, которые вы хотите быть синхронизируются.

Update - вот пример:

grunt.initConfig({ 
    sync: { 
    copy_resources_to_www: { 
     files: [ 
     { cwd: 'src', src: 'img/**', dest: 'www' }, 
     { cwd: 'src', src: 'res/**', dest: 'www' } 
     ] 
    } 
    } 
}); 

УХО означает текущий рабочий каталог. copy_resources_to_www - всего лишь ярлык.

+0

было бы неплохо, если бы у документов было что-то более полезное для чтения. grunt-sync может быть приятным, но примеры очень тупые. – lordB8r

Смежные вопросы