7

I am new to Grunt and to Javascript/Coffeescript altogether.

We are using Grunt in a rather large project with hundreds of .coffee - files. Since Grunt compiles all coffeefiles (although only one file has changed), my initial question was on how to get Grunt to compile only the one changed file. Using stackoverflow I was able to answer that question, thank you all :)

But now it seems that the implemented solution breaks the livereload. When I start with "grunt server" and display my page in the browser, everything looks fine. Then I change one .coffee file and save it. The file gets compiled (I checked), but my browser is never reloaded. Only when I manually reload the browser the new modified code gets displayed.

So the question is: Why does livereload no longer work?

I don't know if this matters, but the Gruntfile was created with yeoman in an older version (with grunt-regarde). I updated the package.json and the Gruntfile to newer specs using grunt-contrib-watch and the buildin livereload. Without the grunt.event.on everything works fine.

Sources (partially):

grunt.initConfig({

    watch: {
            coffee: {
                files: ['<%= yeoman.app %>/coffeescripts/**/*.coffee'],
                tasks: ['coffee:app'],
                options: {
                    nospawn: true
                },
            },
            compass: {
                files: ['<%= yeoman.app %>/styles/**/*.{scss,sass}'],
                tasks: ['compass']
            },
            templates: {
                files: ['<%= yeoman.app %>/templates/**/*.tpl'],
                tasks: ['handlebars']
            },
            livereload: {
                options: {
                    livereload: LIVERELOAD_PORT
                },
                files: [
                    '<%= yeoman.app %>/*.html',
                    '<%= yeoman.tmp %>/styles/**/*.css',
                    '<%= yeoman.tmp %>/scripts/**/*.js',
                    '<%= yeoman.tmp %>/spec/**/*.js',
                    '<%= yeoman.app %>/img/{,*/}*.{png,jpg,jpeg,webp}',
                ]
            }
        },
        coffee: {
            app: {
                expand: true,
                cwd: '<%= yeoman.app %>/coffeescripts',
                src: '**/*.coffee',
                dest: '<%= yeoman.tmp %>/scripts',
                ext: '.js',
                options: {
                    runtime: 'inline',
                    sourceMap: true
                },
            }
        }
    }
});

grunt.event.on('watch', function(action, filepath) {
    filepath = filepath.replace(grunt.config('coffee.app.cwd')+'/', '' );
    grunt.config('coffee.app.src', [filepath]);
});

grunt.registerTask('server', function (target) {
    if (target === 'dist') {
        return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
    }

    grunt.task.run([
        'clean:server',
        'coffee',
        'compass:server',
        'symlink:bower',
        'connect:livereload',
        'handlebars',
        'notify:watch',
        'watch'
    ]);
});

grunt-contrib-watch is used with version v0.4.4, connect-livereload with version 0.2.0

EmilioMg
  • 376
  • 5
  • 14

2 Answers2

0

My solution:

grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        cssmin: {
            dist: {
                expand: true,
                cwd: 'app',
                src: ['**/*.css'],
                dest: 'WebContent'
            }
        },
        uglify: {
            options: {
                mangle: false
            },
            dist: {
                expand: true,
                cwd: 'app/js',
                src: ['**/*.js'],
                dest: 'WebContent/js'
            }
        },
        htmlmin: {
            options: {
                collapseWhitespace: true
            },
            dist: {
                expand: true,
                cwd: 'app',
                src: ['**/*.html'],
                dest: 'WebContent'
            }
        },
        watch: {
            options: {
                spawn: false
            },
            cssmin: {
                files: 'app/css/**/*.css',
                tasks: ['cssmin']
            },
            uglify: {
                files: 'app/js/**/*.js',
                tasks: ['uglify']
            },
            htmlmin: {
                files: 'app/**/*.html',
                tasks: ['htmlmin']
            }
        },
    });

    // Faz com que seja salvo somente o arquivo que foi alterado
    grunt.event.on('watch', function(action, filepath) {
        var tasks = ['cssmin', 'uglify', 'htmlmin'];

        for (var i=0, len=tasks.length; i < tasks.length; i++) {
            var taskName = tasks[i];

            if (grunt.file.isMatch(grunt.config('watch.'+ taskName +'.files'), filepath)) {
                var cwd = new String(grunt.config(taskName + '.dist.cwd')).split('/').join('\\') + '\\'; //inverte as barras e adiciona uma "\" no final
                var pathWithoutCwd = filepath.replace(cwd, ''); //obtem somente o path sem o cwd

                grunt.config(taskName + '.dist.src', pathWithoutCwd); //configura a task
            }   
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-htmlmin');

    // Tarefas padrão
    grunt.registerTask('default', ['cssmin', 'uglify', 'htmlmin']);
};
Wilker Iceri
  • 131
  • 4
  • 12
  • Thank you for your answer, but this didn't work. After small modifications to make it run under my environment I tried your code, and although only the modified coffee-file is compiled, the livereload-task is never triggered after that :( – EmilioMg Aug 20 '13 at 12:44
0

I guess grunt-concurrent is what you're searching for.

Here is my approach. (Note its written in coffee script but you should be able to adapt it easily.)

watch:
  compass:
    files: ['private/compass/**/*.scss']
    tasks: ['compass:dist']
    options:
      livereload: true
  coffee:
    options:
      livereload: 34567
    files: ['private/coffee/**/*/.coffee']
    tasks: ['coffee:dist']
  ci:
    options:
      livereload: 34568
    files: ['application/views/**/*.php', 'application/controllers/**/*.php']

concurrent:
  options:
    logConcurrentOutput: true
  dev: ['watch:compass', 'watch:coffee', 'watch:ci']
YeppThat'sMe
  • 1,812
  • 6
  • 29
  • 45