Angular CLI serve and base href

Several months have passed since Angular 2 was released. Then came Angular CLI promising easier scaffolding and better integration. It’s still in beta and as expected there are things to improve.

One thing that confused me was ng serve and the lack of <base href> support. It’s easy when using ng build with the -bh flag and same feature for serve would’ve been great. Unfortunately the CLI team doesn’t plan on adding base href support 🙁

The project I’m working on relies on multiple other applications and APIs served from other folders. Having base href different than root during development is a must. The only way I found to make the whole setup work was by proxying the needed folder to root.

  • In your index html add the needed <base href>.
    <base href="/project/">
    
  • Create a new file at root called proxy.conf.json and paste:
    [
        {
            "context": [
                "/project"
            ],
            "target": {
                "host": "localhost",
                "protocol": "http:",
                "port": 4200
            },
            "secure": false,
            "pathRewrite": {
                "^/project": "/"
            }
        }
    ]
    
  • Modify your serve command.
    $ ng serve --proxy-config proxy.conf.json --live-reload-base-url /project/ --open true
    

    I set this in package.json start script. After that I can use npm start instead of remembering ng serve and all the parameters.

3 thoughts on “Angular CLI serve and base href

  1. Major reason for using proxy is to proxy the api call. With this, how do I do that?

    For example, if /api/* needs to be forwarded to localhost on port 8080, how do you do that?

    1. You can use the same syntax.

      [
          {
              "context": [
                  "/api"
              ],
              "target": {
                  "host": "localhost",
                  "protocol": "http:",
                  "port": 8080
              },
              "secure": false,
              "pathRewrite": {
                  "^/api": "/api"
              }
          }
      ]
      
  2. I used the {code} ng build -bh /admin/ {code} in the build pipeline as angular app is deployed inside a node.js server where the web services are exposed.

Leave a Reply