Search code examples
javascriptangulargruntjslegacy

Grunt URL rewrite in Angular application on page reload


Here's what the livereload block looks like in Grunt file:

livereload: {
  options: {
    open: true,
    middleware: function(connect, options, middleware) {
      var optBase = typeof options.base === "string" 
        ? [options.base] 
        : options.base;

      return [
        [
          require("connect-modrewrite")(["!(\\..+)$ / [L]"])
        ].concat(
          optBase.map(function(path) { return connect.static(path); })
        ),
        connect.static(".tmp"),
        connect().use("/bower_components", connect.static("./bower_components")),
        connect().use("/app/styles", connect.static("./app/styles")),
        connect.static(appConfig.app)
      ];
    }
  }
}

However, if my URL has a '.' (period) in it, Grunt fails to reload the page. I am using HTML5 Mode in my Angular app and that works fine.

Could I please know what part of

[
  require("connect-modrewrite")(["!(\\..+)$ / [L]"])
].concat(
  optBase.map(function (path) { return connect.static(path); })
)

is causing it to fail and how do I fix this?

Note: It fails only on page reload. The first time I visit the route it works, then if I hit refresh it fails.


Solution

  • Could I please know what part of [this snippet] is causing it to fail and how do I fix this?

    The connect-modrewrite rule here appears to be intended for rewriting non-static-asset URLs only.

    [
      require("connect-modrewrite")(["!(\\..+)$ / [L]"])
    ].concat(
      optBase.map(function (path) { return connect.static(path); })
    )
    

    The rule passed in here, "!(\\..+)$ / [L]", is an inverted URL matching rule to rewrite all URLs that don't contain a period and one or more characters back to the base URL (/). So, if your routes include a period, they will not be rewritten... this is why it fails when live reload runs.

    One suggestion to remedy this is to more explicitly avoid rewrites for requests to static assets:

        require("connect-modrewrite")([
          '!\\.html|\\.js|\\.svg|\\.css|'
          + '\\.scss.*|\\.woff.*|\\.gif.*|\\.png$ '
          // etc...
          + '/ [L]'
        ])
    

    Notice that this rule also begins with an exclamation point (!). Instead of relying solely on the presence of a period, it more explicitly targets URLs that don't include certain file extensions-- along with the period! (:

    Note: code for the suggestion was found on searchcode.com here

    I hope this helps! HMU with any questions, corrections, or well actually-s.