Skip to content

Tweak Paths with Gulp-Connect

August 22nd, 2015 - Software(1 min)

I’ve recently started to work on a front-end project using nodejs, gulp, bower and angular. Its back-end is a java application and it’s configured like this:

  • Serve all the UI (frontend) from a /static path
  • Serve all the API-related URLs with a /dynamic prefix
  • Serve the index.html file (which is part off the front-end) from the root

This is a very nice separation and makes things much clearer for newbies (like me), but I found out the hard way that it creates me some problems as well.

The main culprit is the location of index.html. Since is part of the angular app, it’ll be placed under /static. The java app displays it under /. To make this work, I came up with two options:

  1. Copy index.html at the root of the destination
  2. Make index.html (and the rest of the static things?) visible on both / and /static

Neither of them is that good really simply because it complicates the gulp file a lot. After hunting for an answer online, I got the idea of changing the paths like apache’s mod-rewrite does. This way, index.html could be found from /static and presented to / transparently.

Gulp-connect offers a middleware option:

  root: 'app',
  middleware: function(connect, opt) {
    return [
      // ...

but I could not really figure out how it works. Fortunately, there’s a modrewrite add-on for gulp-connect and the code became

// ...
var connect = require('gulp-connect')
var modRewrite = require('connect-modrewrite')

gulp.task('connect', function(done) {
    root: [paths.connectRoot],
    livereload: true,
    debug: true,
    middleware: function() {
      return [
          '^/static/static/(.*)$ /static/$1 [L]',
          '^/static/(.*)/$ /$1/ [L]',
          '^/dynamic/(.*)$ /dynamic/$1/index.json'

This works nicely for me but can probably be improved a lot :)

The idea is that since index.html is in /static , all relative paths will be /static/static. The first rule allows / to have access to index.html and the second rule cleans the /static/static issue. The last rule will map the API calls to index.json files.


Share on

A little experiment: