-
Notifications
You must be signed in to change notification settings - Fork 757
The BrowserSync API is under development, so features are minimal at the moment.
You can however, already use it within your projects & with task runners such as Gulp using the following API.
##Usage
First, install browser-sync
as a local development dependency.
npm install browser-sync --save-dev
Now use it within your project.
var browserSync = require('browser-sync');
##API - Requires at least version 0.7.0 ###browserSync.init( filePatterns, options, callback );
####filePatterns
Type: String | Array
Default: null
Provide file watching patterns here
// single file pattern
browserSync.init('**/*.css');
// Multiple patterns as array
browserSync.init(['**/*.css', '*.html']);
####options
Type: Object
Default: null
There's a full list of available options here
####callback( err, bs )
Type: Function
The third param given to init()
can be a callback function that gives
you access to the entire BrowserSync Object
var browserSync = require('browser-sync');
var files = "css/*.css";
var options = {
server: {
baseDir: "./"
}
};
browserSync.init(files, options, function(err, bs){
// Full access to BrowserSync object here.
console.log(bs.api.snippet);
console.log(bs.options.url);
// Full access to event emitter
bs.events.on("file:changed", function(data) {
// Custom event handling here
});
});
##Events
Example 1 - Retrieve the HTML snippet
You may want to use the HTML snippet in your own app (for example, if you have your own server setup with custom middleware).
var browserSync = require("browser-sync");
var files = "css/*.css";
var bs = browserSync.init(files, {});
bs.events.on("init", function (api) {
console.log(api.snippet);
});
Example 2 - Retrieving the server/proxy url
You have full access to the internal options
Object via the init
event. So to grab the
URL used in the Server or Proxy, you could do this
var browserSync = require("browser-sync");
var bs = browserSync.init(null, {});
bs.events.on("init", function (api) {
console.log(api.options.url);
});
Example 3 - Listening to file-change events
You might want to be notified when BrowserSync has detected a file-change, you can do that
by listening to the file:changed
event.
var browserSync = require("browser-sync");
var files = "css/*.css";
var options = {
server: {
baseDir: "./"
}
};
var bs = browserSync.init(files, options);
bs.events.on("file:changed", function (file) {
console.log(file.path);
});
Example 4 - Emitting your own file-change events
If you have your own file-watching technique already in place, you can inform BrowserSync about changes
by emitting the file:changed
event. As an example, the following will inject core.css
every 5 seconds.
var browserSync = require("browser-sync");
var bs = browserSync.init(null, {});
// Inject every 5 seconds
setInterval(function () {
bs.events.emit("file:changed", {path: "Users/sites/project/css/style.css"});
}, 5000);