July 26, 2018
Locally serving the build distribution of an Angular SPA
tl;dr
Use Node Package local-web-server and its command ws
with the spa
flag like this: ws --spa index.html
While developing an Angular based SPA usually you will use the Angular CLI as build too. The CLI has an integrated development server which is able to handle client-side routing. So whenever a reload happens and you’re on a route, the browser and the application will stay on this route after the reload without any error. It is a complex team play of the server, the browser and Angular. It is described in detail here at angular.io.
As soon as you build a production ready distribution of your Angular application you loose this comfort. The distribution is stored in dist folder and you can serve it with any HTTP server. There are some packages for Node like http-server and node-static and with Python it is also really easy.
But whenever you’re at a specific route (like http://localhost:8080/my-route
) and hit reload, you will get a 404 error because the file my-route.html does not exist on the server. That’s how the web works.
local-web-server is also an NPM package to start a local server. It has a handy feature: SPA mode. With ws --spa index.html
you can tell the server to deliver the index.html file whenever a file is not found instead of a 404. That’s the same behaviour the dev server of the Angular CLI provides.
The shown procedure does not only work for Angular but for all Single Page Applications, e.g. React or VueJs.