Skip to content

Instantly share code, notes, and snippets.

@soswow
Last active December 14, 2015 10:38
Show Gist options
  • Save soswow/5072917 to your computer and use it in GitHub Desktop.
Save soswow/5072917 to your computer and use it in GitHub Desktop.
Middleware for handle pushState working inside yeoman development server.
  • So, if you start / it will load index.html normally.
  • All assets files has extension rather then .html, so middleware won't interact with the flow
  • If you go to /books middleware will intercept the flow. It calls lrSnippet for augment res.write method to have Live Reload feature event in intercepted pages.
  • The only problem can be if you have any other .html files you want to process normally as static file
  • Pipe thing thanks to https://github.com/thedjpetersen
class App extends Backbone.Router
routes:
'': 'index'
'books': 'booksList'
initialize: ->
console.log "Constructor"
index: ->
console.log "Init page"
booksList: ->
console.log "Booklist"
start: ->
Backbone.history.start pushState: true
window.app = new App()
$ -> app.start()
// Generated on 2013-03-01 using generator-webapp 0.1.5
'use strict';
var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;
var mountFolder = function (connect, dir) {
return connect.static(require('path').resolve(dir));
};
var pushStateHook = function (url) {
var path = require('path');
var request = require('request'); // Need to be added into package.json
return function (req, res, next) {
var ext = path.extname(req.url);
if ((ext == "" || ext === ".html") && req.url != "/") {
req.pipe(request(url)).pipe(res);
} else {
next();
}
};
};
module.exports = function (grunt) {
// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
// configurable paths
var yeomanConfig = {
app: 'app',
dist: 'dist'
};
grunt.initConfig({
// All other configs
connect: {
options: {
port: 9000,
hostname: 'localhost'
},
livereload: {
options: {
middleware: function (connect) {
return [
pushStateHook("http://localhost:9000"),
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, 'app')
];
}
}
},
// All other config
},
// All other config
});
// Standard Gruntfile.js content
};
@szalishchuk
Copy link

Thank you so much, @soswow, for sharing this. I've spent the last couple of hours trying to figure out, how to make the connect's middleware to work as a simple static file server, that will always return index.html, so I could than handle things with backbone router, and I finally did.

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