-
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 ###browserSync.init( filePatterns, options );
####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
####Events (requires version 0.5.7 or above)
The init
method returns an event emitter which you can use in various ways in your own projects, such as
retrieving the HTML snippet, grabbing the URL BrowserSync is using, accessing options etc etc.
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.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.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.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.emit("file:changed", {path: "Users/sites/project/css/style.css"});
}, 5000);