Gulp Watch to build only changed TypeScript

Performance when building TypeScript can be crutial if you are working on a big projects. If you are using watcher to compile when any TypeScript file change and use Gulp Watch to compile every TypeScript file, then you will have a huge performance hit. It means that if you change 1 file that you may have to build thousand of them. The following code is the lazy approach that build every TypeScript file if one changed: + '**/*.ts', ['build', 'tsreload']);

This script watch for TypeScript files to be changed, if it does, run the build task and reload the browser. The problem is that the build task build all TypeScript. To remedy that situation, we want TypeScript to only build the changed file. For that, you will need a new Gulp package called “gulp-cached” that you install as a dev dependency.

npm install gulp-cached --save-dev

Inside your gulpfile.js, you need to access the module:

const changed = require('gulp-cached');

And finally, you need to use the “on change” event after the watch, and remove the tasks’s dependencies."app/scripts/**/*.ts").on("change", function() {
        var compilationResults = gulp.src("app/scripts/**/*.ts")

The main change is that we pipe through the changed call the destination. This pipe, once ran once, will keep data about if the file change. If this one change, it will go down the pipeline. Otherwise, it will be filtered out. It means that the first time a TypeScript file change, the watch will build everything. After, it will only filter all the source down the changed file. The reload is by calling directly connect.reload() at the end. This is a huge performance boost for your as a developer because you will be able, what ever the size of the project you are working on, to build under 1 sec every change you do. Having a rapid window between you save your file and the time you can see your change in your browser is critical to ship fast code. With this library that act a cache, you can benefit of filtering out the noise that doesn’t change and concentrate your computer to build only what is required.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.