Created
June 3, 2020 04:34
-
-
Save danbucholtz/3ac144c6f6e820976ef8ca5850f41591 to your computer and use it in GitHub Desktop.
Script to make TSC Watch and Nodemon play together swimmingly
This file contains 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 { spawn } = require('child_process'); | |
const { join } = require('path'); | |
const chalk = require('chalk'); | |
let tsc = null; | |
let nodemon = null; | |
function getTscPath() { | |
return join(process.cwd(), 'node_modules', '.bin', 'tsc'); | |
} | |
function getNodemonPath() { | |
return join(process.cwd(), 'node_modules', '.bin', 'nodemon'); | |
} | |
function watchTypescript() { | |
return new Promise((resolve) => { | |
tsc = spawn(getTscPath(), ['--watch']); | |
tsc.stdout && tsc.stdout.on('data', (data) => { | |
const output = data.toString(); | |
if (output.includes('Watching for file changes.')) { | |
resolve(); | |
} | |
if (output.includes('Found 0 errors')) { | |
const message = chalk.bold.magentaBright(output); | |
console.log(message); | |
} else { | |
const message = chalk.bold.red(output); | |
console.log(message); | |
} | |
}); | |
tsc.stderr && tsc.stderr.on('data', (data) => { | |
console.log('stderr: ', data.toString()); | |
}); | |
}); | |
} | |
function watchNodemon() { | |
const bootstrapPath = join(process.cwd(), 'dist', 'bootstrap.js'); | |
nodemon = spawn(getNodemonPath(), [bootstrapPath], { stdio: "inherit" }); | |
nodemon.stdout && nodemon.stdout.on('data', (data) => { | |
console.log(data.toString()); | |
}); | |
nodemon.stderr && nodemon.stderr.on('data', (data) => { | |
console.log(data.toString()); | |
}); | |
} | |
let cleanupCalled = false; | |
function cleanup() { | |
if (cleanupCalled) { | |
return; | |
} | |
cleanupCalled = true; | |
if (tsc) { | |
console.log('Cleaning up tsc ...'); | |
tsc.kill(); | |
console.log('Cleaning up tsc ... DONE'); | |
} | |
if (nodemon) { | |
console.log('Cleaning up nodemon ...'); | |
nodemon.kill(); | |
console.log('Cleaning up nodemon ... DONE'); | |
} | |
process.exit(0); | |
} | |
process.on('exit', cleanup); | |
process.on('SIGINT', cleanup); | |
process.stdin.resume(); | |
async function beginListening() { | |
console.log('Starting development mode with initial compile ...'); | |
await watchTypescript(); | |
watchNodemon(); | |
} | |
beginListening(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment