Skip to content

Instantly share code, notes, and snippets.

@dylanscott
Created August 15, 2016 15:35
Show Gist options
  • Save dylanscott/18b9fa1432d80d0cfcf16f9c6711671d to your computer and use it in GitHub Desktop.
Save dylanscott/18b9fa1432d80d0cfcf16f9c6711671d to your computer and use it in GitHub Desktop.
gulp tsc --watch
const gulp = require('gulp')
const gutil = require('gulp-util')
const path = require('path')
const spawn = require('child_process').spawn
const split = require('split')
const prettyHrtime = require('pretty-hrtime')
const TSC_LINE = /\d{1,2}:\d{1,2}:\d{1,2} [AP]M - (.+)/
const TSC_ERROR = /(.+?: )(.+)/
gulp.task('watch:typescript', function(cb) {
const tsc = spawn(path.resolve(__dirname, 'node_modules/.bin/tsc'), ['--watch'], {
cwd: __dirname,
stdio: ['ignore', 'pipe', 'ignore']
})
tsc.on('close', cb)
const taskStart = process.hrtime()
let lastCompilationStart
let errors = []
tsc.stdout.pipe(split())
.on('data', (line) => {
const match = line.match(TSC_LINE)
if (match) {
const message = match[1]
if (message.startsWith('Compilation complete.')) {
if (lastCompilationStart) {
errors.forEach((error) => {
gutil.log(`[${gutil.colors.cyan('typescript')}] ${gutil.colors.red(error.location)} ${error.message}`)
})
gutil.log(`${gutil.colors.cyan('watch:typescript')} finished after ${gutil.colors.magenta(prettyHrtime(process.hrtime(lastCompilationStart)))}.`)
errors = []
} else {
gutil.log(`${gutil.colors.cyan('watch:typescript')} ready after ${gutil.colors.magenta(prettyHrtime(process.hrtime(taskStart)))}.`)
}
} else if (message.startsWith('File change detected.')) {
lastCompilationStart = process.hrtime()
gutil.log(`${gutil.colors.cyan('watch:typescript')} saw file changes.`)
}
} else {
const error = line.match(TSC_ERROR)
if (error) {
errors.push({
location: error[1],
message: error[2],
})
}
}
})
})
@lucastheisen
Copy link

Quite a useful hack until they sort out the issues with gulp-typescrit. One thing though... It doesn't work on windows unless you change .../tsc to .../tsc.cmd.

@mrogunlana
Copy link

I'm wondering how to implement this in gulp 4 since gulp-typescript performance is still slow...

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