Hot code reload in a full stack

I’ve followed the Real World Halogen project in order to get the client-side code auto-reloading successfully. But I also need to interact with a server (for what it’s worth, I’m just using Express for now), and it’d be great to not have to spin up two servers (Express + the dev server Parcel provides).

I tried using parcel watch dev/index.html and then having Express serve that same dev/index.html file, but the dev/index.js file it tries to call fails because require isn’t something understood by the browser. Even if I modify dev/index.html to call dev/index.js as a module (and then use import), I still run into issues because the compiled code in Main.js still uses require.

Any ideas on how to enable auto-reloading for both the server and the client side? Thanks in advance!

Okay, after some more tinkering, I’ve got a solution that works for me.

Relevant directory structure:

├── app.js
├── bin
│   └── www
├── dev
│   ├── index.js
├── public
│   ├── javascripts
├── routes
│   └── index.js
└── views
    └── index.pug

Here’s the relevant bit from my package.json:

  "scripts": {
    "start-server": "node ./bin/www",
    "hot-reload:server": "nodemon --exec npm run start-server",
    "hot-reload:client": "parcel watch dev/index.js -d public/javascripts/",
  },

Here’s my dev/index.js:

require("../output/Main/index.js").main();

My app.js:

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

My views/index.pug:

doctype html
html
  head
    meta(charset='UTF-8')

  body
    script(src='/javascripts/index.js')

And my routes/index.js:

router.get('/', function(req, res, next) {
  res.render('index', {});
});

Now just run the following and you’re good to go:

npm run hot-reload:server
npm run hot-reload:client
3 Likes