Browsersync + Grunt.js
We have an official Plugin for Grunt that makes it easy to incorporate Browsersync into your development workflow. Below are a few examples of common configurations to get you started - use them as a jump-start but don't forget you can also use any of the other Browsersync options as well.
Install ^ TOP
First, you'll need to install the Browsersync Plugin...
$ npm install grunt-browser-sync --save-dev
... and then add this line to your Gruntfile.js
grunt.loadNpmTasks('grunt-browser-sync');
Static File Server ^ TOP
The simplest example would be watching CSS files and using the built-in server for static HTML/CSS/JS files. This config alone will launch a mini-server (using your current working directory as the base), watch your CSS files for changes & auto-inject those changes into all connected browsers.
browserSync: {
bsFiles: {
src : 'assets/css/*.css'
},
options: {
server: {
baseDir: "./"
}
}
}
Proxy ^ TOP
If you already have a local server setup (with your vhosts etc), just tell Browsersync all about it & it will do the rest for you.
browserSync: {
dev: {
bsFiles: {
src : 'assets/css/style.css'
},
options: {
proxy: "local.dev"
}
}
}
+ other watch tasks ^ TOP
Browser Sync is not a replacement for regular watch
tasks (such as compiling SASS, LESS etc),
they are designed to be used together. If you intend to do this, you'll need to set watchTask: true
and be sure to call
the watch task AFTER browserSync. For example, to compile SASS and then inject the CSS into all open browsers
(without a page refresh), your config for all three tasks might look something like this:
// This shows a full config file!
module.exports = function (grunt) {
grunt.initConfig({
watch: {
files: 'app/scss/**/*.scss',
tasks: ['sass']
},
sass: {
dev: {
files: {
'app/css/main.css': 'app/scss/main.scss'
}
}
},
browserSync: {
dev: {
bsFiles: {
src : [
'app/css/*.css',
'app/*.html'
]
},
options: {
watchTask: true,
server: './app'
}
}
}
});
// load npm tasks
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browser-sync');
// define default task
grunt.registerTask('default', ['browserSync', 'watch']);
};
Jump to...