Run a npm script from gulp task

lbrahim picture lbrahim · Apr 14, 2016 · Viewed 34.1k times · Source

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.

Answer

BrunoLM picture BrunoLM · Apr 14, 2016

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.