Search code examples
gruntjsgrunt-contrib-watchgrunt-contrib-copy

Grunt watch to fire different tasks in different environments


After GruntJS generates my CSS+JS, I want it to copy the generated files to the appropriate places on the servers, and so I've set up different grunt-copy tasks to do so. The paths to copy to are different for the development and production environments:

        devjs: {
            src: paths.dest + '/assets/prod.min.js',
            dest: '/srv/www/dev/js/prod.min.js'
        },
        prodjs: {
            src: paths.dest + '/assets/prod.min.js',
            dest: '/srv/www/htdocs/js/prod.min.js'
        },

How can I get grunt watch to know which environment it's in, and so fire the appropriate grunt-copy tasks for that environment? Do I need to have a config file that isn't tracked in the git repo or something that defines the environment, or is there a better way to do so?

Currently my grunt-contrib-watch.js has the following, although I'd like it to only fire copy:devjs OR copy:prodjs depending on the environment.

        js: {
            files: [
                paths.assets + '/**/*.js',
            ],
            tasks: ['js', 'copy:devjs', 'copy:prodjs']
        },

Any ideas? Thanks!


Solution

  • I chose to go with using command-line options for this. So I'd use e.g. grunt watch --enviro=prod on the command line (and cron), and then have this in grunt-contrib-watch.js:

    module.exports = function(grunt) {
    
        var paths = grunt.config.get('paths');
    
        if ( grunt.option( "enviro" ) === 'prod' ) {
            var jsprocess = ['js', 'copy:prodjs'];
        } else if ( grunt.option( "enviro" ) === 'dev' ) {
            var jsprocess = ['js', 'copy:devjs'];
        } else {
            var jsprocess = ['js'];
        }
    
        grunt.config.set(
            'watch',
            {
                options: {
                    expand: true
                },
                css: {
                    files: [
                        paths.assets + '/**/*.*ss',
                    ],
                    tasks: cssprocess
                },...