gruntjs / grunt-contrib-watch

Run tasks whenever watched files change.
http://gruntjs.com/
MIT License
1.98k stars 356 forks source link

Using grunt.config to access JSON object #542

Open johnruane opened 7 years ago

johnruane commented 7 years ago

Can anyone help me access a JSON object using the grunt.config command?

The filepath i want to replace on my 'watch' event is formatted as so:

render: {
  files: [{
    expand: true,
    src: "**/*.nunjucks",
    dest: "build/",
    ext: ".html"
  }]
}

I have tried every combination to access the 'src' property but none work. The documentation only gives the following format as an example: grunt.config('render.files.src', filepath);

johnruane commented 7 years ago

I have figured out the correct syntax, but the tasks is running against all files and not just the changed ones. Can confirm the 'src' is being updated, but the task runs against all files.

module.exports = function(grunt) {
  var changedFiles = Object.create(null);
  var onChange = grunt.util._.debounce(function() {
    grunt.config('nunjucks.render.files.src', Object.keys(changedFiles));
    grunt.log.writeln(grunt.config('nunjucks.render.files.src'));
  }, 200);

  grunt.initConfig({
      nunjucks: {
        options: {
          data: grunt.file.readJSON('data.json'),
          paths: 'html'
        },
      render: {
        files: [ {
      expand: true,
      src: ['**/*.nunjucks'],
      dest: "build/",
      ext: ".html"
    }]
      }
   },
   watch: {
     nunjucks: {
       files: ['html/**/*'],
       tasks: ['nunjucks'],
       options: {
       spawn: false
     }
  }
}
});

grunt.event.on('watch', function(action, filepath) {
  changedFiles[filepath] = action;
  onChange();
});

grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-nunjucks-2-html');
  grunt.registerTask('default', ['nunjucks', 'watch']);
};