Book Image

Grunt Cookbook

By : Jurie-Jan Botha
Book Image

Grunt Cookbook

By: Jurie-Jan Botha

Overview of this book

<p>A web application can quickly turn into a complex orchestration of many smaller components, each one requiring its own bit of maintenance. Grunt allows you to automate all the repetitive tasks required to get everything working together by using JavaScript, the most popular programming language.</p> <p>Grunt Cookbook offers a host of easy-to-follow recipes for automating repetitive tasks in your web application's development, management, and deployment processes. This book will introduce you to methods that can be used to automate basic processes and your favorite tools. By following the recipes, you will soon be comfortable using Grunt to perform a wide array of advanced tasks in a range of different scenarios.</p>
Table of Contents (17 chapters)
Grunt Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Setting up a basic web server


A simple web server will always come in handy during the development process of web-based projects. They can be easily set up and used to serve web content from your local machine, so you don't have to worry about constantly deploying your experimental changes to a remote service provider.

We'll make use of the contrib-connect (0.8.0) plugin, which provides us with the ability to set up and run a simple web server based on the Connect server framework. By default, it will only serve files from a directory, but it has the added benefit of being able to make use of the many Connect middleware plugins available.

Tip

You can read more about the Connect server framework and its middleware plugins at the following URL:

https://github.com/senchalabs/connect

Getting ready

In this example, we'll work with the basic project structure we created in the Setting up Grunt on a project recipe of this chapter. Be sure to refer to it if you are not yet familiar with it's contents.

How to do it...

The following steps take us through setting up a development server that serves files from a directory located in our project directory.

  1. We'll start by installing the package containing the contrib-connect plugin and loading its tasks as given in the instructions provided in the Installing a plugin recipe of this chapter.

  2. With the connect task loaded from the plugin, we can make use of it in our configuration. To do this, we add the following to our configuration:

    connect: {
      server: {
        options: {
          base: 'www',
          keepalive: true
        }
      }
    }

    Tip

    The base option indicates in which directory the server should look for the files that are requested. Everything that you'd like to serve with your development server can be placed in this directory. This includes HTML pages, JavaScript source files, style sheets, images, and so on.

    The keepalive option keeps the server running even if the requested task has finished. This is usually preferred if you're running the connect task on its own, but is not required if another task will be running indefinitely after it has completed.

  3. Let's add a simple file that we'd like to have served from our server so that we have something to test it with. Create a directory called www in the project root, and then a file inside it called index.html, with the following contents:

    <html>
      <head>
        <title>Test Page</title>
      </head>
      <body>
        <h1>This is a test page.</h1>
      </body>
    </html>

    Tip

    Like many other web servers, the Connect server started by this task will always look for an index.html file in a folder if no filename is specified in the request URL.

  4. Now we can run our web server using the grunt connect command, which will produce output indicating that our server started, along with a URL of where it can be reached:

    Running "connect:server" (connect) task
    Waiting forever...
    Started connect web server on http://0.0.0.0:8000
    
  5. Finally, we can use our favorite browser to pay a visit to the URL mentioned in the output. This would show us our example page, as served through our running server:

There's more...

The connect task provides many useful configuration options that allow us to automatically open a browser, specify the port and hostname where the server should run, serve files from more than one directory, use other Connect middleware plugins, and adding extra functionality to the created server.

Opening the default web browser on the default URL

In order to automatically open our favorite web browser on the default URL that our web server provides, we can set the open option to true as we do in the following example:

options: {
  base: 'www',
  keepalive: true,
  open: true
}

Opening a specific web browser at a specific URL

When we'd like to use a different web browser from the default one to open a URL other than the default one, we can provide an object to the open option that specifies exactly what we'd like. The following code specifies a URL, the browser that should be used to open it, and a callback function that should be called once it's been opened:

options: {
  base: 'www',
  keepalive: true,
  open: {
    target: 'http://localhost:8000/test.html',
    appName: 'firefox',
    callback: function() {
      console.log('Test URL opened in Firefox!');
    }
  }
}

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Using a specific port

The default port used by the connect task is 8000, but if you'd like to use a different one, the port option can be used to specify which one you'd like it to be, which is shown in the following code snippet:

options: {
  port: 3000,
  base: 'www',
  keepalive: true
}

Automatically selecting an available port

In case you are not sure about which ports will be available when you start the server, it can be quite useful for you to have the server automatically select an open port. Setting the useAvailablePort option to true will enable this behavior. The code snippet for this is as follows:

options: {
  base: 'www',
  keepalive: true,
  useAvailablePort: true
}

Using a specific hostname

In the case that you'd like the server to attach to a specific hostname and not just the default 0.0.0.0, you can make use of the hostname option in the following manner:

options: {
  base: 'www',
  keepalive: true,
  hostname: 'something.else.com'
}

Serving files from multiple directories

If you have more than one directory that contains the files that you'd like to be serving, then the base option can be provided with an array of directory names to look up content. Here is a code snippet for your reference:

options: {
  base: ['www', 'other'],
  keepalive: true
}

Tip

When using an array for the base option, the server will look up the requested resources in each of the directories, from left to right, and return a resource as soon as it's found. If each of the two directories in the example contained an index.html file, a request to the root URL would return the index.html file in the www directory.

Using middleware

If we'd like to use one of the many existing middleware plugins available for the Connect framework, we can set the middleware option to a function that modifies the middleware stack by adding the desired middleware to it.

  1. First, we'll need to install the middleware that we'd like to use, which in our case is packaged along with the Connect server framework. We can install the framework package using the following command:

    $ npm install --save connect
    
  2. Now, we alter the options of the server target in the connect task so that it adds the compress middleware to the stack:

    options: {
      base: 'www',
      keepalive: true,
      middleware: function(connect, options, middlewares) {
        middlewares.push(
          require('connect').middleware.compress()
        );
        return middlewares;
      }
    }

    Tip

    The middleware option can also be set to an array, but this will replace the default stack that is provided by the connect task. The default middleware allows the serving of files from the directories indicated by the base option.

Adding functionality to the created server

There are times that it would be useful to work with the server that is created by the connect task. A good example of this is when we'd like to enable our server to handle Socket.IO interactions. This can be done by providing a function to the onCreateServer option that works with the created server in whichever way you like:

options: {
  base: 'www',
  keepalive: true,
  onCreateServer: function(server, connect, options) {
    var io = require('socket.io').listen(server);
    io.sockets.on('connect', function (socket) {
      // do something with socket
    });
  }
}

Tip

This example assumes that you've already installed the socket.io package. You can find out more about socket.io at its website:

http://socket.io/