Skip to content

Instantly share code, notes, and snippets.

Created December 27, 2012 21:29
Show Gist options
  • Save anonymous/4392152 to your computer and use it in GitHub Desktop.
Save anonymous/4392152 to your computer and use it in GitHub Desktop.
Custom Grunt Connect Middleware to rewrite non static/directory resources to index.html. Useful for debugging AngularJS apps with HTML5 mode enabled. Routes like /projects which have been defined by the $routeProvider can then be navigated directly from the browser by serving always the index.html. Angular will automatically resolve the defined …
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
connect: {
server: {
options: {
port: 9001,
base: 'target/build/debug/app',
middleware: function(connect, options) {
var fs = require('fs');
var util = require('util');
var path = require('path');
return [
// Serve static files.
connect.static(options.base),
// Make empty directories browsable.
connect.directory(options.base),
//rewrite all non static/directories resources to index.html, no redirect!
function(req, res, next) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
var stream = fs.createReadStream(path.join(options.base, 'index.html'));
util.pump(stream, res);
}
];
}
}
}
}
});
//##############################################################
//# Dependencies
//###############################################################
grunt.loadNpmTasks('grunt-contrib-connect');
//###############################################################
// # Alias tasks
//###############################################################
grunt.registerTask('default', ['connect']);
}
@ataube
Copy link

ataube commented Dec 27, 2012

ups, accidentally published this gist anonymously...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment