Angular 8 run dist folder on npm run start-dev

Viewed 3312

I am trying to run my dist folder directly instead of doing ng serve. For that I wrote a script in package.json.

start-dev: ng build && http-server dist

The problem is I want it to auto run whenever I save any file. Also it will build the whole npm again which is a very slow procedure. Any other method on how I can do it? And do it faster?

3 Answers

You can use the --watch flag when you run ng build. So the command will be ng build --watch to auto rebuild when you change a file.

To auto restart the http-server dist/<app_name> command you can use nodemon

With nodemon the command would be nodemon --watch dist --exec 'http-server dist/<app_name>'

You can run both commands together like this ng build --watch & nodemon --watch dist --exec 'http-server dist/<app_name>'

The above commands will work together. Angular will rebuild the dist folder and nodemon will restart your server when the dist folder changes.

Like indicated in Chris' answer, you can automatically rebuild your app when using ng build --watch.

If you just want to serve the latest version of your app, you can disable caching from http-server (which is on by default), using -c-1 option (doc)

On linux (use single & to run scripts in parallel)

"start-dev": "ng build --watch & http-server -c-1 dist", 

On windows (notice the start command):

"start-dev": "start ng build --watch && start http-server -c-1 dist", 

Notes

  • Your browser has probably already cached the files dist before you deactivate the cache like above, so clear the cache manually once. You won't need to to that after

  • This solution will not reload the page, you have to do it yourself

  • http-server does not support fallbacks, which might be a problem if you are using angular's default strategy. So if you were on http://localhost:8080/module1/path1 and you reload the page, you'll get a 404. You need to reload http://localhost:8080 and navigate to the correct url from the app router

  • Depending on your angular.json, the output folder might be dist, dist/projectName, or dist/projectName/browser, or whatever you indicated

Better you should install lite-server. For install lite-server:-

npm install --global lite-server

then open the dist folder in cmd or terminal

lite-server

Resource:- https://www.npmjs.com/package/lite-server

Related