Created
April 12, 2018 19:08
-
-
Save jcblw/cfed88cd73d9002b4bedc69011baf553 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const padEnd = require('string.prototype.padend'); | |
const gaze = require('gaze'); | |
const util = require('util'); | |
const _ = require('lodash'); | |
const chalk = require('chalk'); | |
const { exec, spawn } = require('child_process'); | |
const pexec = util.promisify(exec); | |
const log = (type, color = 'yellow') => (info, infoColor = 'reset') => { | |
const tag = chalk[color](padEnd(type, 7)); | |
const sep = chalk.grey('|'); | |
const infoSerialized = chalk[infoColor](info.trim()); | |
process.stdout.write(`${tag}${sep} ${infoSerialized}\n\r`); | |
}; | |
function build() { | |
return pexec('yarn run build'); | |
} | |
function createServer() { | |
const server = spawn('yarn', ['start'], { env: process.env }); | |
const serverLog = log('server', 'blue'); | |
const serverErrorLog = log('error', 'red'); | |
server.stdout.on('data', data => serverLog(data.toString('utf8'))); | |
server.stderr.on('data', data => | |
serverErrorLog(data.toString('utf8'), 'red')); | |
return server; | |
} | |
function killServer(child) { | |
if (!child) return; | |
child.stdin.pause(); | |
child.kill(); | |
} | |
function recompile(config) { | |
if (config.isCompiling) return; | |
const { server } = config; | |
const infoLog = log('info'); | |
Object.assign(config, { isCompiling: true }); | |
infoLog('Recompiling source', 'grey'); | |
build().then(() => { | |
infoLog('Source recompiled', 'grey'); | |
infoLog('Restarting server', 'grey'); | |
killServer(server); | |
const newServer = createServer(); | |
infoLog(`New server running ${newServer.pid}`, 'grey'); | |
Object.assign(config, { | |
server: newServer, | |
isCompiling: false, | |
}); | |
}); | |
} | |
const recompileDebounced = _.debounce(recompile, 500); | |
function startWatching() { | |
const config = {}; | |
// initial compile | |
recompile(config); | |
gaze('src/**/*.js', function watch() { | |
this.on('all', () => { | |
recompileDebounced(config); | |
}); | |
}); | |
} | |
startWatching(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment