How to get grunt-watch to live reload HTML changes under different build tasks

北战南征 提交于 2019-12-07 16:40:47

问题


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:


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



来源:https://stackoverflow.com/questions/19382708/how-to-get-grunt-watch-to-live-reload-html-changes-under-different-build-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!