Automating tasks with Grunt

In many software projects, there are a number of tasks that are typically automated. For instance, just as a traditional C++ or Java project would need to compile the source code into byte code, a JavaScript project might need to use RequireJS or CoffeeScript to compile its source. The project might also need to concatenate files, run linting programs to validate the source, or assemble other web components such as sprite image files or SCSS/Less-generated CSS files.

Most of these tasks aren't language-specific: you don't need to actually use JavaScript code in order to start RequireJS Optimizer; you just need a command line. Because of this, it's possible to use a tool designed for another language (such as Ant or Maven for Java, or Fabric for Python) to automate these tasks, and if your server-side team is using such a language, it might be helpful to have everyone using the same tool.

However, if you don't have a server-side team (or if that team uses Node.js), you may wish to have a JavaScript-specific build tool, and this is where Grunt comes in. Here's an example Grunt configuration file that can be used to run RequireJS Optimizer:

module.exports = function(grunt) {
    grunt.initConfig({
        requirejs: {
            app: {
                options: {
                    findNestedDependencies: true,
                    mainConfigFile: 'public/js/config.js',
                    baseUrl : 'public/js',
                    name : 'app',
                    out : 'build.js',
                    optimize : 'none'
                }
            }
        }
    });
    grunt.loadNpmTasks('grunt-contrib-requirejs'),
    grunt.registerTask('default', ["requirejs"]);
};

While a full explanation of the preceding code is outside the scope of this book, it is sufficient to say that by using this configuration file, you can run a single command at the command line to invoke RequireJS Optimizer. More importantly, you can make RequireJS Optimizer just one step of your entire deployment process and then, invoke that entire process by using a single command. You can also use Grunt to set up different processes for different environments, such as one process for setting up a development environment and a different one for setting up a production server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.84.169