Monthly Archives: January 2017

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 /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.