How to get grunt-watch to live reload HTML changes

2019-05-16 03:43发布

I can easily set up my Grunt file to live reload HTML and SCSS changes by doing something like:

watch: {
    options: {
        livereload: true,
    },
    css: {
        files: ['scss/*.scss'],
        tasks: ['compass']
    },
    html: {
        files: ['index.html'],
        tasks: ['build']
    }
}

However, I have a build task for dev environment: dev, and a build task for production environment: build. Therefore, calling build when the HTML is changed will build the site for production which is not what I want if I only want the dev version.

Ideally I would do something like:

watch: {
    options: {
        livereload: true,
    },

    dev: {
        html: {
            files: ['<%%= yeoman.app %>/*.html',
                    '<%%= yeoman.app %>/**/*.html'],
            tasks: ['dev']
        },

        css: {
            files: ['<%%= yeoman.app %>/assets/scss/*.scss'],
            tasks: ['compass']
        }
    },

    dist: {
        html: {
            files: ['<%%= yeoman.app %>/*.html',
                    '<%%= yeoman.app %>/**/*.html'],
            tasks: ['build']
        },

        css: {
            files: ['<%%= yeoman.app %>/assets/scss/*.scss'],
            tasks: ['compass'],
        }
    }
}

Thereby being able to call watch:dev or watch:dist, however this code does not work.

The only work-around I can figure out is to have:

…
    dev: {
        files: ['<%%= yeoman.app %>/*.html',
                '<%%= yeoman.app %>/**/*.html',
                '<%%= yeoman.app %>/assets/scss/*.scss'],
        tasks: ['dev']
    },

    dist: {
        files: ['<%%= yeoman.app %>/*.html',
                '<%%= yeoman.app %>/**/*.html',
                '<%%= yeoman.app %>/assets/scss/*.scss'],
        tasks: ['build']
    }
…

Again calling watch:dev or watch:dist, but the downside to this is that I don't want to be rebuilding the whole site when I'm just changing a small amount of SCSS.

Is there any way to achieve what I am after?

1条回答
萌系小妹纸
2楼-- · 2019-05-16 04:23

Try a dynamic alias task:

grunt.registerTask('watchit', function(type) {
  grunt.config('watch.html.tasks', type);
  grunt.task.run('watch');
});

Then call it with grunt watchit:build or grunt watchit:dev to switch between the two.

More info here: http://gruntjs.com/frequently-asked-questions#dynamic-alias-tasks

查看更多
登录 后发表回答