Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically run gulp tasks after saving some of javascript files in Visual Studio

I have a folder in my asp.net project that contains some javascript files. Just before building project, they are minified and copied to "wwwroot" folder using gulp. It works great, but when I make some changes to any of javascript files, I have to restart entire project (to run tasks connected with building) or manually run tasks from "Task Runner Explorer".

It takes some time and it is quite irritating. Is it some way to run those tasks as soon as I save any of javascript files in this folder?

like image 369
Piotrek Avatar asked Jan 03 '16 10:01

Piotrek


People also ask

How do I run a gulp file in Visual Studio?

Run a Gulp Task in Visual Studio CodeType "Run Task" and select it, which will bring up a list of tasks configured in Gulp. Choose the Gulp Task you want to run! Most of your Gulp Tasks will probably be automated using gulp watch, but manual Gulp Tasks can easily be run within Visual Studio Code.

What is Gulpfile js used for?

Gulp purely uses the JavaScript code and helps to run front-end tasks and large-scale web applications. It builds system automated tasks like CSS and HTML minification, concatenating library files, and compiling the SASS files. These tasks can be run using Shell or Bash scripts on the command line.


1 Answers

You should use gulp.watch. I've just migrated some build scripts from Grunt to Gulp, and wanted to provide the same functionality.

Just add a watch task to your Gulpfile:

gulp.task('watch', function() {
    gulp.watch('/path/to/your/css/**/*.css', ['minifyCss']);
});

When you run this task gulp does not exit after the task is completed. Instead when a file changes, the task(s) specified in the second argument will run. If you do not want to minify all CSS files when a file changes, gulp-cached package will come in handy. It filters files which are not modified since the task run last time (in a single Gulp running session, not between Gulp runs). Just add it after the gulp.src call in your task and it will filter the files which modified.

var cached = require('gulp-cached'),
    cssnano = require('gulp-cssnano');

gulp.task('minifyCss', function() {
    return gulp.src('/path/to/your/css/**/*.css')
        .pipe(cached('cssFiles'))
        .pipe(cssnano()) // or whatever plugin you use for minification
        .pipe(gulp.dest('./dist/'));
}

I did try to run my task similar to this one from the VS Task Runner, but it does not like the ES6 features used in my Gulpfile so I do not know whether it is working fine with continuously running tasks. However it is working as intended from command line.

like image 174
qcz Avatar answered Sep 28 '22 02:09

qcz