Search code examples
javascriptgruntjsgrunt-contrib-watchbabeljs

Grunt: run babel task for each file instead of entire directory


I have this Grunfile, which "watch" for a .js files in a src/ directory and when one of them is modified, the babel (https://github.com/babel/grunt-babel) task runs to generate ES5 files in a dist/ directory:

module.exports = function(grunt) {

    require('load-grunt-tasks')(grunt);
    grunt.initConfig({
        babel: {
            options: {
                sourceMap: false
            },

            dist: {
                 files: [{
                    expand: true,
                    cwd: 'src/',
                    src: ['*.js'],
                    dest: 'dist/',
                    ext: '.js'
                }]
            }

        },

        watch: {
            ej6: {
                files: "src/*.js",
                tasks: ['babel']
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');

    grunt.registerTask('default', ['babel', 'watch']);

};

Is it possible to watch the src/ directory and run the babel task only for that specific file? Because, if I have 'n' files in src/ path, the script will regenerate all of them.


Solution

  • Try using this package https://www.npmjs.com/package/grunt-newer

    I using the gulp equivalent following a similar approach as you described.