docs/recipes/minimal-browsersync-setup-with-gulp4.md
BrowserSync is a great tool to streamline the development process with the ability to reflect code changes instantaneously in the browser through live-reloading. Setting up a live-reloading BrowserSync server with Gulp 4 is very clean and easy.
npm install --save-dev browser-sync
src/
scripts/
|__ index.js
dist/
scripts/
index.html
gulpfile.babel.js
The goal here is to be able to:
src/scripts/, e.g. compiling with babel, minifying, etc.dist/scripts for use in index.htmldist packagedist package, reload the browser to immediately reflect the changesThe gulpfile could be broken in 3 parts.
Refer to the main README for more information.
import babel from 'gulp-babel';
import concat from 'gulp-concat';
import del from 'del';
import gulp from 'gulp';
import uglify from 'gulp-uglify';
const paths = {
scripts: {
src: 'src/scripts/*.js',
dest: 'dist/scripts/'
}
};
const clean = () => del(['dist']);
function scripts() {
return gulp.src(paths.scripts.src, { sourcemaps: true })
.pipe(babel())
.pipe(uglify())
.pipe(concat('index.min.js'))
.pipe(gulp.dest(paths.scripts.dest));
}
And write the tasks to serve and reload the server accordingly.
import browserSync from 'browser-sync';
const server = browserSync.create();
function reload(done) {
server.reload();
done();
}
function serve(done) {
server.init({
server: {
baseDir: './'
}
});
done();
}
This is trivially accomplished with gulp.series
const watch = () => gulp.watch(paths.scripts.src, gulp.series(scripts, reload));
The last step is to expose the default task
const dev = gulp.series(clean, scripts, serve, watch);
export default dev;
And profit
$ gulp
Now if you go to http://localhost:3000, which is the default address of the BrowserSync server, you will see that the end result in the browser is updated everytime you change the content of the source file. Here is the whole gulpfile:
import babel from 'gulp-babel';
import concat from 'gulp-concat';
import del from 'del';
import gulp from 'gulp';
import uglify from 'gulp-uglify';
import browserSync from 'browser-sync';
const server = browserSync.create();
const paths = {
scripts: {
src: 'src/scripts/*.js',
dest: 'dist/scripts/'
}
};
const clean = () => del(['dist']);
function scripts() {
return gulp.src(paths.scripts.src, { sourcemaps: true })
.pipe(babel())
.pipe(uglify())
.pipe(concat('index.min.js'))
.pipe(gulp.dest(paths.scripts.dest));
}
function reload(done) {
server.reload();
done();
}
function serve(done) {
server.init({
server: {
baseDir: './'
}
});
done();
}
const watch = () => gulp.watch(paths.scripts.src, gulp.series(scripts, reload));
const dev = gulp.series(clean, scripts, serve, watch);
export default dev;