Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Last active October 11, 2017 16:23
Show Gist options
  • Save simenbrekken/47574c3303db671adac04c307d6fbfb3 to your computer and use it in GitHub Desktop.
Save simenbrekken/47574c3303db671adac04c307d6fbfb3 to your computer and use it in GitHub Desktop.
Express.js brute-force ☕️-reloading

This neat little script let's you develop Express apps without using something like nodemon to reload your server between changes.

Usage:

  1. Put dev.js outside your project source folder, scripts/dev.js is what I'm using.
  2. Make sure your actual app in src/index.js exports the Express instance itself without listening:
import express from 'express'

const app = express()
app.use('/foo', (req, res) => res.send('Bar'))

export default app
  1. Run node scripts/dev and enjoy.
const express = require('express')
const chokidar = require('chokidar')
const babelRegister = require('babel-register')
const path = require('path')
const sourcePath = path.resolve(__dirname, '../src')
babelRegister({
only: sourcePath
})
const watcher = chokidar.watch(sourcePath)
watcher.on('ready', () => {
watcher.on('all', () => {
Object.keys(require.cache).filter(key => key.startsWith(sourcePath)).forEach(key => {
delete require.cache[key]
})
})
})
let handler = require(sourcePath)
const app = express()
app.use((req, res, next) => {
handler = require(sourcePath).default
handler(req, res, next)
})
const port = process.env.PORT || 8081
const host = process.env.HOST || 'localhost'
app.listen(port, host, err => {
if (err) {
throw err
}
console.log(`Listening at http://${host}:${port}`)
})
@mariuslundgard
Copy link

Nice reference! Think line 27 in dev.js needs to be handler = require(sourcePath).default?

@simenbrekken
Copy link
Author

simenbrekken commented Oct 4, 2017

@mariuslundgard Forgot to mention we're using https://github.com/59naga/babel-plugin-add-module-exports to work around having to use .default all over the place. I've updated the Gist though since most people won't have it installed.

@mariuslundgard
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment