grunt-connect-route

Provides RewriteRules middleware for the grunt connect and express.

grunt-connect-route

This plugin provides RewriteRules middleware for the Grunt Connect / Express.

This plugin requires Grunt ~0.4.1

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-connect-rewrite --save-dev

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-connect-route');

In your project's Gruntfile, add a section named rules to your existing connect definition. Please note that unlike options, rules cannot be set per server, so the rules attribute must always be nested directly under 'connect'.

grunt.initConfig({
    connect: {
        options: {
            port: 9000,
            hostname: 'localhost'
        },
        rules: {
            '^/index_dev.html$': '/src/index.html',
            '^/js/(.*)$': '/src/js/$1',
            '^/css/(.*)$': '/public/css/$1',
            '^/api/(.*)': 'require!/app/api/$1.js',
            '^/api/(.*)' : 'http://l-wap1.test.com:8080/api/$1',
        }
    }
})

You may also optionally read rules from a different grunt config, like so:

grunt.initConfig({
    express: {
        options: {
            port: 9000
        },
        server: {
            hostname: 'localhost'
        },
        rules: {
            '^/index_dev.html$': '/src/index.html',
            '^/js/(.*)$': '/src/js/$1',
            '^/css/(.*)$': '/public/css/$1'
        }
    },
    configureRewriteRules: {
        options: {
            rulesProvider: 'express.rules'
        }
    }
}
})

Include helper to use in the middleware (add this line to the top of the grunt file):

var rewriteRulesSnippet = require('grunt-connect-route/lib/utils').rewriteRequest;

Add the RewriteRules snippet to the connect option middleware hook

connect: {
    development: {
        options: {
            middlewarefunction (connect) {
                return [
                    rewriteRulesSnippet, // RewriteRules support 
                    connect.static(require('path').resolve(options.base)) // mount filesystem 
                ];
            }
        }
    }
}

For the server task, add the "configureRewriteRules" task before the "connect" task

grunt.registerTask('server', function (target) {
    grunt.task.run([
        'configureRewriteRules',
        'connect:development'
    ]);
});

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.

  • 2013.07.27 v0.1.1 Add possibility to read settings from custom grunt config path
  • 2013.04.12 v0.1.0 Initial Release