Search code examples
javascriptnode.jstypescriptgulptsc

Run a npm script from gulp task


How to run a npm script command from inside a gulp task?

package.json

"scripts": 
{
    "tsc": "tsc -w"
}

gulpfile.js

gulp.task('compile:app', function(){
  return gulp.src('src/**/*.ts')
    .pipe(/*npm run tsc*/)
    .pipe(gulp.dest('./dist'))
    .pipe(connect.reload());
});

I want to do this because running npm run tsc does not give me any error but if I use gulp-typescript to compile .ts then I get bunch of errors.


Solution

  • You can get the equivalent using gulp-typescript

    var gulp = require('gulp');
    var ts = require('gulp-typescript');
    
    gulp.task('default', function () {
      var tsProject = ts.createProject('tsconfig.json');
    
      var result = tsProject.src().pipe(ts(tsProject));
    
      return result.js.pipe(gulp.dest('release'));
    });
    
    gulp.task('watch', ['default'], function() {
      gulp.watch('src/*.ts', ['default']);
    });
    

    Then on your package.json

    "scripts": {
      "gulp": "gulp",
      "gulp-watch": "gulp watch"
    }
    

    Then run

    npm run gulp-watch
    

    Alternatively using shell

    var gulp = require('gulp');
    var shell = require('gulp-shell');
    
    gulp.task('default', function () {
      return gulp.src('src/**/*.ts')
        .pipe(shell('npm run tsc'))
        .pipe(gulp.dest('./dist'))
        .pipe(connect.reload());
    });
    

    gulp-shell has been blacklisted you can see why here

    Another alternative would be setting up webpack.