I wanted to improve a code quality of my TypeScript project, so I decided to add linting to my gulp build process. My original build task looked pretty straightforward
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function buildTypeScript() { return gulp.src(['app/**/*.ts','typings/**/*.ts']) .pipe(sourcemaps.init()) .pipe(ts({ sortOutput: true, noExternalResolve: true, noEmitOnError: true, target: 'ES5' })) .pipe(concat(constants.appall)) .pipe(sourcemaps.write()) .pipe(gulp.dest(paths.app)); } |
and according to gulp-tslint manual adding linting requires including only two additional lines of code
1 2 3 4 |
//.. .pipe(tslint()) .pipe(tslint.report('verbose')); //.. |
This works fine until you start using type definitions (d.ts files) from external resources (which is the usual way of combining TypeScript with existing JavaScript libraries). Usually these files have different code styling rules than our own, which means that our build will fail.
There are couple of ways of solving this problem. The obvious one is to split the task into two separate tasks, one for linting and one for building, but in my opinion a much cleaner way is to use gulp-filter. Gulp-filter has an ability to filter the stream on the fly, but what is more interesting it can also restore it to previous unfiltered state. Using these two features we can filter the stream from d.ts files before linting process begins and then restore the stream and pass it to TypeScript compiler. We can do it with two additional lines of code. Improved build script is presented below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function buildTypeScript() { // include all typescript files but exclude definitions var filter = gulpFilter(['**/*.ts', '!**/*d.ts']); return gulp.src(['app/**/*.ts','typings/**/*.ts']) .pipe(filter) // use the filter .pipe(tslint()) .pipe(tslint.report('prose', { emitError: true })) .pipe(filter.restore()) // clear filter .pipe(sourcemaps.init()) .pipe(ts({ sortOutput: true, noExternalResolve: true, noEmitOnError: true, target: 'ES5' })) .pipe(concat(constants.appall)) .pipe(sourcemaps.write()) .pipe(gulp.dest(paths.app)); } |
Source code for this post can be found here