4

For the life of me I can't get Browser Sync and Nodemon to run nicely alongside my Express server. I have tried every combination I can imagine.

My Express server runs at port 5000 which I can open and view, nodemon runs when changes are made, great but the browser still doesn't 'hot refresh' so to speak. I would like for the browser window to either refresh or open a new tab after nodemon has restarted the server.

package.json scripts

"scripts": {
"start": "node app.js",
"dev": "set NODE_ENV=DEV&& nodemon app.js 5000 browser-sync start --proxy localhost:5000 -e * --ignore=node_modules --reload-delay 10 --no-ui --no-notify",
"ui": "node app.js browser-sync start nodemon app.js --port=5001 --proxy=localhost:5000 -e * --ignore=node_modules --reload-delay 10 --no-ui --no-notify",
"ui2": "nodemon start & browser-sync start --proxy 'localhost:5000' -e * --ignore=node_modules"
},

I just want to start my express server, listen for changes with nodemon then restart, then either reload browser window or launch a new one to see the changes. Please help me understand what I am missing?

ZADorkMan
  • 301
  • 4
  • 19

2 Answers2

3

In case someone has the same problem, the aha moment was when I realized I needed to open a 2nd terminal window to run browser-sync. And using the below scripts in package.json now works beautifully!

So first run npm run start/dev depending if you want server restarts on changes or not then open a 2nd terminal window and run npm run ui`. In my case my app.js is launching on port 8000.

package.json

 "scripts": {
    "start": "node app.js",
    "dev": "nodemon -e * app.js",
    "ui": "browser-sync start --proxy localhost:8000 --files=**/*  --ignore=node_modules --reload-delay 10000 --no-ui --no-inject-changes"
  },

app.js - const port = process.env.PORT || '8000';

ZADorkMan
  • 301
  • 4
  • 19
  • I'm having an issue with this. Do you have any idea what the cause may be? https://stackoverflow.com/questions/74400841/browser-sync-infinite-reload – chocojunkie Nov 11 '22 at 10:42
2

This can be run (npm start) in parallel with modules "npm-run-all" or with "concurrently" (replace string after start: with the string after start_b:).

  "scripts": {
    "browsersync": "browser-sync start --proxy localhost:5000 --files 'public,views'",
    "nodemon": "nodemon server.js",
    "start_b": "concurrently --kill-others \"npm run nodemon\" \"npm run browsersync\" ",
    "start": "npm-run-all -p nodemon browsersync"
  },

In my system, I had problems tracking .njk files, because the browser reloaded after changing them but without actually updating changes. I had to use a nodemon.json file to add the folder (views/) and extension .njk:

{
  "watch": ["server.js", "views/"],
  "ext": "js, css, njk"
}
Ferroao
  • 3,042
  • 28
  • 53
  • Please also note that you'll need to install the `npm-run-all` package if you haven't already (for ease, you can install it globally: ```npm i npm-run-all -g``` ) – Deolu A May 18 '23 at 23:48