Gulp, a task runner, can be used with
BrowserSync
for live reloading to enhance development efficiency. To achieve this, first install both Gulp and
BrowserSync
using npm (Node Package Manager).
Create a ‘
gulpfile.js
’ at the root of your project directory. This file will contain tasks that Gulp will execute. Define a task named ‘
serve
’ in
gulpfile.js
. In this task, initialize
BrowserSync
with server setup pointing to the base directory of your project.
Next, define another task called ‘
reload
’. This task should call the reload function of
BrowserSync
whenever changes are detected in your files. Use Gulp’s watch method to monitor changes in your
HTML, CSS,
or JS files
. When any change is detected, it triggers the ‘
reload
’ task causing
BrowserSync
to refresh all connected browsers.
Here’s an example :
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
gulp.task('serve', function(done) {
browserSync.init({
server: "./"
});
done();
});
gulp.task('reload', function (done) {
browserSync.reload();
done();
});
gulp.task('watch', gulp.series('serve', function () {
gulp.watch("./*.html", gulp.series('reload'));
}));​
To start watching for changes, run gulp watch command in terminal.