Introduction to Browser Sync
Browser Sync is an essential tool for web developers to synchronize file changes across multiple devices and browsers in real-time. It enhances productivity significantly by allowing instant feedback on code changes. In this article, we will explore the rich set of APIs provided by Browser Sync and learn how to implement them in your web development projects.
Getting Started
To get started with Browser Sync, you need to install it via npm:
npm install -g browser-sync
Once installed, you can initiate Browser Sync with a single command:
browser-sync start --server --files "css/*.css"
Browser Sync APIs
1. .init()
Initialize Browser Sync with options. This method is used to configure the settings and start the server.
const browserSync = require('browser-sync').create();
browserSync.init({
server: "./app",
files: ["./app/css/*.css", "./app/js/*.js", "./app/*.html"]
});
2. .reload()
Manually reload all browsers that are connected to Browser Sync.
browserSync.reload();
3. .stream()
Inject changes into the browser without reloading. This is particularly useful for CSS changes.
gulp.task('css', function() {
return gulp.src('src/*.css')
.pipe(browserSync.stream());
});
4. .watch()
Watch files and automatically trigger events like reload or stream.
browserSync.watch('app/*.html').on('change', browserSync.reload);
5. .notify()
Display a notification in the browser when files change.
browserSync.notify("Compiling, please wait!");
Example App Using Browser Sync
Let’s build a simple web app that uses Browser Sync for live reloading and CSS injection:
const browserSync = require('browser-sync').create();
const gulp = require('gulp');
gulp.task('serve', function() {
browserSync.init({
server: "./app"
});
gulp.watch("app/*.html").on('change', browserSync.reload);
gulp.watch("app/css/*.css").on('change', browserSync.stream);
});
gulp.task('default', gulp.series('serve'));
In the above example, we create a Gulp task named ‘serve’ that initializes Browser Sync, watches HTML files for changes to reload the browser, and watches CSS files for changes to inject the new styles without reloading the browser.
By integrating Browser Sync into your development workflow, you can save time and enhance your productivity. Try it out in your next web development project!
Hash: 833ef5debac959e20186163ecc2b532e3eccc4c4d42de2f5a809e3e0248f63b7