Hooking up express.js with Angular CLI in dev environment

NEW ANSWER

My experience of 15 hours has taught me that trying to serve an Angular app with Express during development is NOT a good idea. The proper way is to run Angular and Express as two different apps on two different ports. Angular will be served on port 4200 and Express on port 3000 as usual. Then configure a proxy for API calls to Express app.

Add proxy.config.json to root of Angular project:

{
  "/api/*":{
    "target":"http://localhost:3000",
    "secure":false,
    "logLevel":"debug"
  }
}

Open up a new terminal tab and run this command to start Express app:

nodemon [YOUR_EXPRESS_APP.js] --watch server

(YOUR_EXPRESS_APP.js is usually named server.js or app.js. server is a directory where you keep all your Express app files)

Open up a second terminal tab and run this command to start Angular app:

ng serve --proxy-config proxy.config.json

This will ensure that Angular app is rebuilt and browser reloaded when a change is made to any Angular app file. Similarly, Express server will restart when a change is made to any Express app files.

Your Angular app is here: http://localhost:4200/

Watch this video to see how to configure a proxy for your API calls with Angular CLI

NOTE: this setup only applies for development environment. In production, you will want to run ng build and place the Angular app inside a dist directory to be served up by Express. In production, there is only ONE app running - an Express app serving up your Angular app.

PREVIOUS ANSWER

Using input from @echonax I came up with this solution which is quite fast:

  • Add Express to Angular 2 app (built with Angular CLI) as in this tutorial
  • Run this in terminal:

ng build -w & nodemon server.js --watch dist --watch server

This will rebuild the Angular app into the dist folder, and the node server will restart each time that happens. However, there is NOT automatic browser refresh with this setup :(

More on that here:

https://github.com/jprichardson/reload


"etayluz" solution is very good. But I want to add an additional option for NEW ANSWER to not opening two times terminal.

Firstly you have to install concurrently package (https://www.npmjs.com/package/concurrently);

npm install concurrently --save 

Then you could add below codes into your package.json file.

"start": "concurrently \"npm run serve-api\" \"npm run serve\"",
"serve": "ng serve --port 3333 --proxy-config proxy.config.json", // You could add --port for changing port
"serve-api": "nodemon [YOUR_EXPRESS_APP.js] --watch server",

npm start is enough for running your project.


Using angular-cli, the ng build or ng build --prod command will give you bundled up files along with an index.html. Make your app.js(node/express) target this file.

Example:

app.use( express.static(__dirname + '/src' ) ); //<- it will automatically search for index.html under src folder.