I was getting really frustrated recently when trying to deploy my Angular 2 applications live to gh-pages branch to host the sites through Github. I had started Angular 2 projects from three different starter projects (Angular CLI, FountainJS, and Angular Webpack Starter), but all three of them were giving me errors when I deployed the site live! Here's the story of what was happening and how I fixed the issues.
I was getting this error when deploying an application scaffolded from Angular CLI:
Then I moved over and tried it on a starter project from the AngularClass's "angular2-webpack-starter" project, but it was giving me these very similarly terrifying errors:
After fixing the errors in all three projects I can now say that the problems all stemmed from the base url for my projects being "/". This slash means it's an absolute url, and especially when deploying to gh-pages, you should use relative urls instead of absolute. This can normally be solved by changing the slash to a dot! The dot ( . ) represents a relative url, and changing this is the correct spot fixed my projects! Now, in the rest of this post I'll go into specifically where to make this slash-to-dot change in each of the three projects.
For the project that was scaffolded from the Angular CLI using ng new I was able to fix the errors by changing this one single line of code from '/' to './'
This piece of code was line 9 of app/src/index.html (although that may change over time). After I built the project again and deployed, it worked!
I was still getting a strange error in the console about "ember live reload" not being found, but at least my app was running!
I had also scaffolded out a project from the yeoman "generator-fountain-webapp". This is a really nice one, and I especially like it because it gives you the option to set up ngRx (Angular 2 Redux) for your project. I was getting similar errors when deploying this project to gh-pages as well, but I was able to fix them by changing the slash to a dot! For this project, the change happeded at line 4 of app/index.html:
Changing it from "/" to "./" worked, and my deployed site ran cleanly with no errors. Sweet!
I opened up this issue and asked this question on stack overflow. Eventually I was able to find the baseUrl for this project. Since this one was scaffolded from the Angular 2 Webpack Starter the line to change was in a slightly different location. For this project I found it on line 22 of config/webpack.common.js, and I just needed to change it from '/' to '.'
Then I built the project, added the files to git, and pushed to gh-pages. It works!
The posts on this site are written and maintained by Jim Lynch. About Jim...