### IServerOption Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/types.md An example demonstrating how to configure the server option with base directories, an index file, and route mappings. ```typescript const server: IServerOption = { baseDir: ['./dist', './assets'], index: 'index.html', directory: false, routes: { '/api': 'http://localhost:3001' } }; ``` -------------------------------- ### Example: Custom Build Event Workflow Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/events.md Demonstrates a custom event workflow where a 'build:started' event is emitted, and a 'build:complete' event is listened for to trigger a browser reload. ```javascript const browserSync = require('browser-sync'); browserSync.init({ server: true }, (err, bs) => { // Emit custom build event bs.events.emit('build:started', { timestamp: Date.now() }); // Listen to build events bs.events.on('build:complete', (data) => { console.log('Build finished at', new Date(data.timestamp)); bs.reload(); }); }); ``` -------------------------------- ### Install browser-sync globally Source: https://github.com/browsersync/browser-sync/wiki/Installation Install the browser-sync npm module globally to use it as a command-line tool. Ensure Node.js is installed first. ```bash npm install -g browser-sync ``` -------------------------------- ### Example BrowsersyncProxy Configuration Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/types.md Illustrates how to create a BrowsersyncProxy object with target, URL map, and custom middleware. Ensure 'immutable' is installed for the Map type. ```typescript import { Map } from 'immutable'; const proxy: BrowsersyncProxy = { target: 'http://localhost:8080', url: Map({ protocol: 'http:', hostname: 'localhost', port: '8080', path: '/' }), middleware: [ (req, res, next) => { req.headers['x-forwarded-for'] = req.ip; next(); } ] }; ``` -------------------------------- ### Middleware Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/types.md An example of a middleware configuration object for handling requests to the '/api/users' route. ```typescript const mw: Middleware = { route: '/api/users', id: 'custom-users-api', handle: (req, res, next) => { res.json({ users: [] }); } }; ``` -------------------------------- ### Start BrowserSync with Configuration File Source: https://github.com/browsersync/browser-sync/wiki/Working-with-a-Config-File Execute this command in the same directory as your `bs-config.js` file to launch BrowserSync with your custom settings. ```bash browser-sync start --config bs-config.js ``` -------------------------------- ### init() Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browsersync-core.md Initializes and starts a BrowserSync instance. This function can accept a configuration object and a callback function for post-initialization actions. ```APIDOC ## init() ### Description Initialize and start a BrowserSync instance. ### Method `init(config?: BrowserSyncOptions, callback?: (error: Error | null, instance: BrowserSync) => void): BrowserSync` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (Object) - Optional - Configuration object with BrowserSync options. See [Configuration](/configuration.md) for available options. - **callback** (Function) - Optional - Callback function invoked when BrowserSync has completed initialization. Receives error (if any) and the BrowserSync instance. ### Request Example ```js const browserSync = require('browser-sync'); browserSync.init({ server: { baseDir: './dist' }, port: 3000, files: ['dist/**/*'] }, function(err, bs) { if (err) { console.error(err); return; } console.log('BrowserSync started on port 3000'); console.log('Local URL:', bs.options.getIn(['urls', 'local'])); }); ``` ### Response #### Success Response (BrowserSync Instance) - **BrowserSync instance** (`BrowserSync`) - The BrowserSync instance with methods for controlling the service. #### Response Example (See Request Example for context of `bs` object) ERROR HANDLING: - Error if instance is already running - Error if configuration validation fails ``` -------------------------------- ### Initialize BrowserSync Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/README.md Starts BrowserSync with server, file watching, and port configuration. Logs the local URL upon readiness. ```javascript const browserSync = require('browser-sync'); browserSync.init({ server: './dist', files: ['dist/**/*'], port: 3000, ghostMode: true, notify: true }, (err, bs) => { console.log('Ready on', bs.options.getIn(['urls', 'local'])); }); ``` -------------------------------- ### BrowserSync UI API: Get Options Response Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Example response structure for the GET /api/options endpoint, showing current BrowserSync configuration. ```typescript { port: 3000, mode: "server", ghostMode: { ... }, urls: { ... } } ``` -------------------------------- ### Set start path for browser Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Define the URL path that BrowserSync should open in the browser when it starts. This path is relative to the server root. ```javascript { startPath: '/dashboard' } ``` -------------------------------- ### GET / Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Serves the main UI HTML page. ```APIDOC ## GET / ### Description Serves the main UI HTML page. ### Method GET ### Endpoint / ``` -------------------------------- ### Initialize BrowserSync Instance Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browsersync-core.md Initializes and starts a BrowserSync instance with specified configuration and an optional callback for post-initialization actions. Use this to set up the server, port, and files to watch. ```javascript const browserSync = require('browser-sync'); browserSync.init({ server: { baseDir: './dist' }, port: 3000, files: ['dist/**/*'] }, function(err, bs) { if (err) { console.error(err); return; } console.log('BrowserSync started on port 3000'); console.log('Local URL:', bs.options.getIn(['urls', 'local'])); }); ``` -------------------------------- ### Create and Serve BrowserSync Client Middleware Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/client-script-injection.md This example shows how to create Express/Connect middleware using `browserSync.middleware()` to serve the BrowserSync client script. It also demonstrates how to serve the script content directly as a string. ```javascript const browserSync = require('browser-sync-client'); const express = require('express'); const app = express(); // Use as middleware const scriptContent = browserSync.minified(); const clientMiddleware = browserSync.middleware( {}, scriptContent, 'middleware' ); app.get('/browser-sync/socket.io.js', clientMiddleware); // Or serve as static file const scriptString = browserSync.middleware( {}, scriptContent, 'file' ); console.log(scriptString.substring(0, 100)); // First 100 chars ``` -------------------------------- ### BrowserSync Client Notification UI Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-client.md An example of the HTML structure for the small notification popup that appears in the browser corner. ```html

File compiled successfully!

``` -------------------------------- ### BsTempOptions Usage Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/types.md Demonstrates how to create and access options using the BsTempOptions type with Immutable.js methods. ```typescript const options: BsTempOptions = Map({ server: 'src', port: 3000, ghostMode: { clicks: true } }); // Access with immutable methods const port = options.get('port'); // 3000 const clicks = options.getIn(['ghostMode', 'clicks']); // true ``` -------------------------------- ### BrowserSync UI API: Get Connections Response Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Example response structure for the /api/connections endpoint, listing connected browsers. ```typescript [ { id: "socket-id", ua: "Mozilla/5.0...", address: "192.168.1.100", connectedAt: 1234567890 } ] ``` -------------------------------- ### GET /api/options Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Retrieves the current BrowserSync configuration options. ```APIDOC ## GET /api/options ### Description Get current BrowserSync options. ### Method GET ### Endpoint /api/options ### Response #### Success Response (200) - **port** (number) - The port BrowserSync is running on. - **mode** (string) - The current mode (e.g., 'server', 'proxy'). - **ghostMode** (object) - Configuration for ghost mode features. - **urls** (object) - Object containing various URLs related to the BrowserSync instance. ### Response Example ```json { "port": 3000, "mode": "server", "ghostMode": { ... }, "urls": { ... } } ``` ``` -------------------------------- ### Browser Event Listener Setup Source: https://github.com/browsersync/browser-sync/blob/master/packages/browser-sync-client/test/fixtures/index.html Sets up a click event listener on an element, accounting for older browser compatibility using attachEvent. ```javascript var old = window.addEventListener ? false : true; // alert(old); var elem = document.getElementById("shower"); var elem2 = document.getElementById("toggle"); elem[old ? "attachEvent" : "addEventListener"]((old ? "on" : "") + "click", function () { console.log("~~~~~Click event occured~~~~~~"); }, true); ``` -------------------------------- ### Event Listening Plugin Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md This plugin listens for file changes and client connections, logging relevant information to the console. ```javascript module.exports = { plugin: function(options, bs, cb) { // Listen to file changes bs.events.on('file:changed', function(file) { console.log('File changed:', file); }); // Listen to client connections bs.events.on('client:connected', function(data) { console.log('Browser connected:', data.ua); }); if (cb) cb(); }, 'plugin:name': 'event-logger' }; ``` -------------------------------- ### Example Code Block Source: https://github.com/browsersync/browser-sync/blob/master/packages/browser-sync-ui/test/fixtures/index.html This snippet demonstrates a basic code block within the HTML structure. It is intended to showcase how code examples are rendered. ```html Example code block ``` -------------------------------- ### Accessing Local URL (BrowserSync 1.x) Source: https://github.com/browsersync/browser-sync/blob/master/README.md Example of how to access the local URL in BrowserSync version 1.x. ```javascript browserSync({server: true}, function(err, bs) { console.log(bs.options.urls.local); }); ``` -------------------------------- ### Access Top-Level BrowserSync Options Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browsersync-core.md Illustrates how to get specific top-level configuration settings directly from the BrowserSync instance's options. ```javascript const port = bs.options.get('port'); const mode = bs.options.get('mode'); ``` -------------------------------- ### Simple Plugin Implementation Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md A basic example of a plugin module that exports a `plugin` function and a `plugin:name`. The `plugin` function logs a message and optionally calls a callback. ```javascript module.exports = { plugin: function(options, bs, cb) { // Initialize plugin console.log('Plugin initialized'); // Optional: do async work if (cb) cb(); }, 'plugin:name': 'my-plugin' }; ``` -------------------------------- ### BrowserSync Initialization with Socket.IO Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/socket-io-integration.md Demonstrates how to initialize BrowserSync with ghost mode enabled. BrowserSync automatically initializes Socket.IO, which can be accessed via `bs.io` to listen for client connections and events. ```typescript import { init } from 'browser-sync/lib/sockets'; const http = require('http'); const browserSync = require('browser-sync'); browserSync.init({ server: true, ghostMode: { clicks: true, scroll: true } }, (err, bs) => { // Socket.IO is initialized automatically by BrowserSync // but can also be accessed via bs.io const io = bs.io; // Listen to connections io.on('connection', (socket) => { console.log('Client connected:', socket.id); }); }); ``` -------------------------------- ### Configure BrowserSync with npm Scripts Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/index.md This JSON configuration shows how to start BrowserSync using an npm script. It serves files from the 'dist' directory and watches for changes in 'dist/**/*' to trigger reloads. ```json { "scripts": { "dev": "browser-sync start --server dist --files dist/**/*" } } ``` -------------------------------- ### Cleanup Plugin Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md This plugin registers a cleanup task to close a custom server instance when BrowserSync shuts down. ```javascript module.exports = { plugin: function(options, bs, cb) { const server = require('some-library').createServer(); server.listen(9000); // Register cleanup task bs.registerCleanupTask(function() { server.close(); console.log('Cleanup complete'); }); if (cb) cb(); }, 'plugin:name': 'custom-server' }; ``` -------------------------------- ### Middleware Plugin Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md This plugin adds custom middleware to the BrowserSync server, allowing for custom request headers. ```javascript module.exports = { plugin: function(options, bs, cb) { // Add custom middleware to server const middleware = (req, res, next) => { res.setHeader('X-Custom', 'header-value'); next(); }; const serverOptions = bs.options.get('server'); if (serverOptions && serverOptions.middleware) { // Middleware is added to chain } if (cb) cb(); }, 'plugin:name': 'middleware-plugin' }; ``` -------------------------------- ### BrowserSync Client CSS Injection Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-client.md Illustrates how the client updates a CSS link tag to cache-bust the file when injecting CSS. ```html ``` -------------------------------- ### once(event, callback) Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/events.md Registers a listener that will be executed only the first time a specified event occurs. This is ideal for setup tasks or actions that should only happen once. ```APIDOC ## once(event, callback) ### Description Register a listener that fires only the first time the event occurs. ### Method `once` ### Parameters #### Path Parameters - **event** (string) - Required - The name of the event to listen for. - **callback** (Function) - Required - The function to execute when the event is triggered for the first time. ### Request Example ```javascript bs.events.once('service:init', () => { console.log('First init only'); }); ``` ``` -------------------------------- ### Plugin with Hooks Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Demonstrates a plugin that defines a hook for 'service:exit'. This hook function is executed when BrowserSync is shutting down, allowing for cleanup operations. ```javascript module.exports = { plugin: function(options, bs, cb) { // Set up plugin instance const instance = {}; if (cb) cb(); return instance; }, 'plugin:name': 'my-plugin', hooks: { 'service:exit': function(bs) { // Clean up when BrowserSync exits console.log('BrowserSync shutting down'); } } }; ``` -------------------------------- ### Accessing Local URL (BrowserSync 2.x) Source: https://github.com/browsersync/browser-sync/blob/master/README.md Example of how to access the local URL in BrowserSync version 2.x using immutable data structures. ```javascript browserSync({server: true}, function(err, bs) { console.log(bs.options.getIn(["urls", "local"])); }); ``` -------------------------------- ### Handle file:changed Event (JavaScript) Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/events.md A simplified JavaScript example to log the path of a modified file when the 'file:changed' event occurs. ```javascript bs.events.on('file:changed', (change) => { if (change.event === 'change') { console.log(`Modified: ${change.file}`); } }); ``` -------------------------------- ### Custom Client JS Hook Implementation Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Example of implementing the 'client:js' hook to return custom JavaScript code for injection into clients. ```javascript module.exports = { plugin: function(options, bs, cb) { if (cb) cb(); }, hooks: { 'client:js': function() { return 'console.log("Custom client code");'; } } }; ``` -------------------------------- ### Build Pipeline Integration with Gulp Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/events.md Integrate BrowserSync events into a Gulp build pipeline. This example shows how to emit and listen for custom build events. ```javascript const browserSync = require('browser-sync'); const gulp = require('gulp'); const sass = require('gulp-sass'); browserSync.init({ server: true }, (err, bs) => { bs.events.on('build:start', () => { console.log('Build started'); }); gulp.watch('src/**/*.scss', ['scss']); }); gulp.task('scss', function() { bs.events.emit('build:start'); return gulp.src('src/**/*.scss') .pipe(sass()) .pipe(gulp.dest('dist/css')) .on('finish', () => { bs.events.emit('build:finish', { type: 'scss' }); }); }); ``` -------------------------------- ### Initialize BrowserSync Configuration File Source: https://github.com/browsersync/browser-sync/wiki/Working-with-a-Config-File Run this command in your project's root directory to create a `bs-config.js` file. ```bash browser-sync init ``` -------------------------------- ### Initialize BrowserSync in Snippet Mode Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/index.md Ideal for minimal setup, this mode injects a JavaScript snippet into pages and works with any server. It is limited to snippet injection and does not support CSS injection. ```javascript browserSync.init({ // No server or proxy configured }); ``` -------------------------------- ### UI Instance Methods: init() Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Initializes the UI server, setting up the Express/Connect server, Socket.IO namespace, static file serving, and client-side routes. This method is typically called automatically by the plugin. ```APIDOC ## UI Instance Methods: init() ### Description Initializes the UI server. This method is called automatically by the plugin and sets up the Express/Connect server, Socket.IO namespace for the UI, static file serving, and client-side routes. ### Method `init(): void` ### Parameters This method does not accept any parameters. ``` -------------------------------- ### WebSocket Proxy Mode Server Setup Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/socket-io-integration.md Code for setting up a separate HTTP server for WebSocket connections when BrowserSync is in proxy mode with `proxy.ws: true`. It listens on a configured port and registers a cleanup task to close the server. ```typescript if ( bs.options.get("mode") === "proxy" && bs.options.getIn(["proxy", "ws"]) ) { // Creates a new server for WebSocket connections server = utils.getServer(null, bs.options).server; server.listen(bs.options.getIn(["socket", "port"])); // Register cleanup task bs.registerCleanupTask(() => { server.close(); }); } ``` -------------------------------- ### TransformFn Usage Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/types.md Provides an example of a TransformFn implementation that determines and sets the 'mode' option based on other incoming options. ```typescript const setMode: TransformFn = (incoming: BsTempOptions) => { const mode = incoming.get('server') ? 'server' : incoming.get('proxy') ? 'proxy' : 'snippet'; return [incoming.set('mode', mode), []]; }; ``` -------------------------------- ### plugin() Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Initializes the BrowserSync UI server. This function sets up the UI control interface and makes it accessible. ```APIDOC ## Function: plugin() Initialize the BrowserSync UI server. ### Signature ```typescript function plugin( options: UIOptions, bs: BrowserSync, callback?: Function ): UI ``` ### Parameters #### Parameters - **options** (`UIOptions`) - Required - UI configuration options. - **bs** (`BrowserSync`) - Required - BrowserSync instance reference. - **callback** (`Function`) - Optional - Initialization callback function. ### Returns `UI` — The initialized UI instance with methods for control. ### Example ```js const browserSync = require('browser-sync'); browserSync.init({ server: true, ui: { port: 3001, weinre: { port: 8081 } } }, (err, bs) => { // UI is automatically initialized // Access at http://localhost:3001 }); ``` ``` -------------------------------- ### service:init Event Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/events.md Fired after BrowserSync has completed its initialization process, indicating that the server is ready. ```APIDOC ## service:init Event ### Description Fired after BrowserSync has completed initialization. ### When After all plugins are loaded and the server is listening. ### Usage ```javascript bs.events.on('service:init', function() { console.log('BrowserSync initialized and ready'); }); ``` ``` -------------------------------- ### Get Minified BrowserSync Client Script Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/client-script-injection.md Retrieves the minified version of the BrowserSync client script. Use this to get the script's size in bytes. ```javascript const browserSync = require('browser-sync-client'); const script = browserSync.minified(); console.log(script.length); // Minified size in bytes ``` -------------------------------- ### init() Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Initializes all plugins that have been registered with BrowserSync. This method is typically called automatically during the BrowserSync startup process. ```APIDOC ## init() ### Description Initialize all registered plugins within the BrowserSync system. ### Method Signature ```typescript init(): void ``` ### Usage This method is called automatically during BrowserSync initialization and generally does not require manual invocation by the user. ``` -------------------------------- ### Configure Static Server with Multiple Directories Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Serve static files from multiple local directories by providing an array of directory paths. BrowserSync will serve files from all specified locations. ```javascript { server: ['./dist', './assets'] } ``` -------------------------------- ### Initialize BrowserSync with Configuration Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Use this snippet to initialize BrowserSync with common configuration options like server, port, files, and ghostMode. The callback function handles initialization errors and logs the ready port. ```javascript const browserSync = require('browser-sync'); browserSync.init({ server: { baseDir: './dist' }, port: 3000, files: ['dist/**/*'], ghostMode: { clicks: true, scroll: true } }, (err, bs) => { if (err) console.error(err); console.log('Ready on port', bs.options.get('port')); }); ``` -------------------------------- ### GET /api/connections Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Returns an array of connected browsers with their details. ```APIDOC ## GET /api/connections ### Description Returns array of connected browsers. ### Method GET ### Endpoint /api/connections ### Response #### Success Response (200) - **id** (string) - The unique identifier for the connection. - **ua** (string) - The user agent string of the connected browser. - **address** (string) - The IP address of the connected client. - **connectedAt** (number) - Timestamp indicating when the connection was established. ### Response Example ```json [ { "id": "socket-id", "ua": "Mozilla/5.0...", "address": "192.168.1.100", "connectedAt": 1234567890 } ] ``` ``` -------------------------------- ### TransformResult Usage Example (No Errors) Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/types.md Illustrates the structure of a TransformResult tuple when no errors occur during option transformation. ```typescript const [opts, errors]: TransformResult = [ Map({ port: 3000 }), [] // No errors ]; ``` -------------------------------- ### BrowserSync Configuration Patterns Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/README.md Illustrates common configuration options for setting up BrowserSync in server or proxy mode, including file watching and ghost mode. ```javascript // Server mode { server: 'dist' } ``` ```javascript // Proxy mode { proxy: 'http://localhost:8080' } ``` ```javascript // File watching { files: 'dist/**/*' } ``` ```javascript // Ghost mode control { ghostMode: { clicks: true, scroll: false } } ``` ```javascript // Custom middleware { middleware: (req, res, next) => { /* ... */ } } ``` -------------------------------- ### Registering a Service Exit Hook Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Example of programmatically registering a hook to execute code when the service exits. ```javascript module.exports = { plugin: function(options, bs, cb) { // Register hook programmatically bs.pluginManager.hook('service:exit', function() { console.log('Exiting...'); }); if (cb) cb(); }, hooks: { 'file:changed': function(file, event, bs) { console.log('File changed:', file, event); } } }; ``` -------------------------------- ### Configure Static Server with Full Object Options Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Utilize the full configuration object for the static server to specify base directories, index file, directory listing, custom routes, and middleware. This offers granular control over the server's behavior. ```javascript { server: { baseDir: ['./dist', './assets'], index: 'index.html', directory: false, routes: { '/api': 'http://localhost:3001' }, middleware: [ (req, res, next) => { res.setHeader('X-Custom-Header', 'value'); next(); } ] } } ``` -------------------------------- ### Configure UI Server with Boolean Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Use `ui: true` to enable the UI server with default port 3001. ```javascript { ui: true // Use default port 3001 } ``` -------------------------------- ### Get Plugin Instance Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Retrieves a specific plugin instance by its name. Ensure the plugin is already registered. ```typescript get(name: string): any ``` ```javascript const logger = bs.pluginManager.get('logger'); ``` -------------------------------- ### One-Time Listeners Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/events.md Register a listener that will only be executed once using the `once` method. This is useful for setup tasks that should only occur at initialization. ```APIDOC ## One-Time Listeners ### Description Register a listener that will only be executed once using the `once` method. This is useful for setup tasks that should only occur at initialization. ### Method `bs.events.once(event, fn)` ### Parameters #### Event Name - **event** (string) - The name of the event to listen for. #### Callback Function - **fn** (function) - The function to execute once when the event is emitted. ### Request Example ```javascript bs.events.once('service:init', () => { console.log('Only fires once'); }); ``` ``` -------------------------------- ### init() Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/socket-io-integration.md Initializes the Socket.IO server for BrowserSync communication, handling WebSocket and fallback transports. ```APIDOC ## init() ### Description Initializes the Socket.IO server for BrowserSync communication. This function sets up the real-time communication channel between the server and connected browsers using Socket.IO. ### Function Signature ```typescript export function init(server: http.Server, clientEvents: string[], bs: BrowserSync): Server ``` ### Parameters #### Parameters - **server** (`http.Server`) - Required - HTTP server instance to attach Socket.IO to. - **clientEvents** (`string[]`) - Required - Array of event names to register for ghost mode (e.g., `['scroll', 'click', 'input']`). - **bs** (`BrowserSync`) - Required - BrowserSync instance for accessing options and events. ### Returns `Server` — Socket.IO Server instance with connection handler already attached. ### Configuration The Socket.IO server is configured using options from `bs.options`: #### Options - **socket.namespace** (`string`) - Socket.IO namespace (default: `/browser-sync`). Can be a function returning a string. - **socket.path** (`string`) - Socket.IO path on the server (default: `/browser-sync/socket.io`). - **socket.socketIoOptions** (`Object`) - Additional Socket.IO configuration options. - **socket.clients.heartbeatTimeout** (`number`) - Client heartbeat timeout in milliseconds. - **socket.port** (`number`) - Port for WebSocket server when in proxy mode. - **ghostMode** (`boolean`) - Enable ghost mode for event mirroring across clients. - **proxy.ws** (`boolean`) - Enable WebSocket proxying (creates separate server if true). ### Example ```typescript import { init } from 'browser-sync/lib/sockets'; const http = require('http'); const browserSync = require('browser-sync'); browserSync.init({ server: true, ghostMode: { clicks: true, scroll: true } }, (err, bs) => { // Socket.IO is initialized automatically by BrowserSync // but can also be accessed via bs.io const io = bs.io; // Listen to connections io.on('connection', (socket) => { console.log('Client connected:', socket.id); }); }); ``` ``` -------------------------------- ### Plugin Options Configuration Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Details how to pass configuration options to a plugin during BrowserSync initialization. ```APIDOC ## Plugin Options Configuration ### Description Pass custom configuration options to your registered plugins by including them in the `browserSync.init()` configuration object. The plugin's name is used as the key for its options. ### Method `browserSync.init(options)` ### Parameters #### `options` (object) - **server** (boolean | object) - Server configuration. - **[pluginName]** (object) - An object containing configuration settings specific to the plugin named `[pluginName]`. This key should match the name used during `browserSync.use()`. ### Request Example ```javascript browserSync.init({ server: true, myPlugin: { setting1: 'value1', setting2: 42 } }, (err, bs) => { // Plugin will receive { setting1: 'value1', setting2: 42 } as its options }); ``` ### Plugin Signature with Options Plugins receive their options as the first argument to their `plugin` function. ```javascript // In your plugin module module.exports = { plugin: function(options, bs, cb) { const setting1 = options.setting1; // 'value1' const setting2 = options.setting2; // 42 if (cb) cb(); } }; ``` ``` -------------------------------- ### TransformResult Usage Example (With Errors) Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/types.md Shows a TransformResult tuple containing transformed options and an array of error objects. ```typescript const [opts2, errors2]: TransformResult = [ Map({ port: 3000 }), [ { type: 'PORT_ERROR', level: 'error', errors: [{ error: new Error('Port already in use') }] } ] ]; ``` -------------------------------- ### Configure UI Server with Object Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Specify custom port and host for the UI server by providing an object to the `ui` option. ```javascript { ui: { port: 3001, host: 'localhost' } } ``` -------------------------------- ### Configure Plugin Options via BrowserSync Init Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Illustrates how to pass custom options to a plugin during the BrowserSync initialization process. These options are then available within the plugin. ```javascript browserSync.init({ server: true, myPlugin: { setting1: 'value1', setting2: 42 } }, (err, bs) => { // Plugin receives options }); ``` -------------------------------- ### BrowserSync Client Debouncing Example Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-client.md Illustrates debouncing of rapid events, such as multiple scroll events being emitted only every 100ms. ```typescript // Multiple scroll events // Single emit every 100ms ``` -------------------------------- ### Initialize UI Server Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Called automatically by the plugin to set up the Express/Connect server, Socket.IO namespace, static file serving, and client-side routes. ```typescript ui.init(): void ``` -------------------------------- ### Immutable Options Access Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/index.md Accessing options from an Immutable.js Map. Use `get` for top-level keys and `getIn` for nested keys. ```javascript const port = bs.options.get('port'); const urls = bs.options.getIn(['urls', 'local']); ``` -------------------------------- ### Registering a Plugin Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Explains the process of registering a new plugin with BrowserSync using the `browserSync.use()` method. ```APIDOC ## Registering a Plugin ### Description Register a plugin with BrowserSync by calling `browserSync.use()`. This makes the plugin available for initialization and use within the BrowserSync instance. ### Method `browserSync.use(name, module)` ### Parameters - **name** (string) - The name to register the plugin under. - **module** (object) - The plugin module, which must export a `plugin` function. ### Request Example ```javascript const browserSync = require('browser-sync'); // Assuming 'my-plugin-module' exports the plugin structure browserSync.use('my-plugin', myPluginModule); ``` ### Plugin Structure ```javascript // In my-plugin-module.js module.exports = { plugin: function(options, bs, cb) { // Plugin logic here if (cb) cb(); } }; ``` ``` -------------------------------- ### Automatically open local URL Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Configure BrowserSync to automatically open the local URL in the default browser when it starts. This is the default behavior. ```javascript { open: 'local' } ``` -------------------------------- ### Initialize BrowserSync in Server Mode Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/index.md Use this mode to serve static files from local directories. It leverages Express for serving files and supports features like directory listing and route mapping. ```javascript browserSync.init({ server: { baseDir: ['./dist', './assets'] } }); ``` -------------------------------- ### get() Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browsersync-core.md Retrieves a previously created named BrowserSync instance. This is useful for interacting with an existing instance, such as triggering reloads or accessing its configuration. ```APIDOC ## Function: get() ### Description Retrieve a previously created named BrowserSync instance. ### Signature ```typescript function get(name: string): BrowserSync ``` ### Parameters #### Path Parameters - **name** (string) - Required - The identifier of the instance to retrieve. ### Returns `BrowserSync` — The requested BrowserSync instance. ### Throws `Error` — If instance with the given name does not exist. ### Example ```js const browserSync = require('browser-sync'); // Initialize with a name browserSync.init({ server: true }, { name: 'dev' }, (err, bs) => { // Later, retrieve the instance const instance = browserSync.get('dev'); instance.reload(); }); ``` ``` -------------------------------- ### BrowserSync Event Listening Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/README.md Demonstrates how to listen for file changes and browser connections, and how to emit custom events. ```javascript // File changes bs.events.on('file:changed', (change) => { console.log(change.file, change.event); }); ``` ```javascript // Browser connections bs.events.on('client:connected', (data) => { console.log('Browser UA:', data.ua); }); ``` ```javascript // Custom events bs.events.emit('custom:event', { data: value }); ``` -------------------------------- ### Configure Static Server with Single Directory Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Enable a static server by specifying a single local directory to serve files from. This is a simple way to serve your project's static assets. ```javascript { server: './dist' } ``` -------------------------------- ### Initializing BrowserSync UI Server Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Initializes the BrowserSync UI server with custom port and WEinRE configurations. The UI will be accessible via the specified port. ```javascript const browserSync = require('browser-sync'); browserSync.init({ server: true, ui: { port: 3001, weinre: { port: 8081 } } }, (err, bs) => { // UI is automatically initialized // Access at http://localhost:3001 }); ``` -------------------------------- ### Listen for service:init Event Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/events.md Execute a function after BrowserSync has completed its initialization process. ```javascript bs.events.on('service:init', function() { console.log('BrowserSync initialized and ready'); }); ``` -------------------------------- ### Configure IP Address to Listen On Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Set the IP address BrowserSync should listen on. Defaults to 'localhost'. Use '0.0.0.0' to listen on all available network interfaces. ```javascript { listen: '0.0.0.0' // Listen on all interfaces } ``` -------------------------------- ### get(name) Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Retrieves a specific plugin instance from the plugin manager by its name. This allows you to access and use the functionality of an already registered plugin. ```APIDOC ## get(name) ### Description Retrieve a plugin instance by its registered name. ### Method Signature ```typescript get(name: string): any ``` ### Parameters #### Path Parameters - **name** (string) - Required - The name of the plugin to retrieve. ### Example ```javascript const loggerPlugin = bs.pluginManager.get('logger'); ``` ``` -------------------------------- ### Get Unminified BrowserSync Client Script Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/client-script-injection.md Retrieves the unminified, readable version of the BrowserSync client script. This is useful for debugging or custom modifications. ```javascript const browserSync = require('browser-sync-client'); const script = browserSync.unminified(); // Use for debugging or custom modifications fs.writeFileSync('debug-client.js', script); ``` -------------------------------- ### Enable HTTPS with Custom Certificate Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Configure HTTPS using your own SSL certificate and key files. Ensure the paths to `key.pem` and `cert.pem` are correct. ```javascript { https: { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') } } ``` -------------------------------- ### Static File List for Watching Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/file-watching.md Specify an array of file patterns to watch. This is useful for targeting specific build output directories. ```javascript { files: ['dist/**/*.html', 'dist/**/*.css', 'dist/**/*.js'] } ``` -------------------------------- ### Hybrid File Watching Approach Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/file-watching.md Combine watching built files with automatic watching of source files. Use 'watchOptions' to control initial behavior. ```javascript { files: 'dist/**/*', // Built files watch: true, // Also watch source (with auto-ignores) watchOptions: { ignoreInitial: true } } ``` -------------------------------- ### BrowserSync UI API: Update Options Payload Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Example payload for the POST /api/options endpoint to update BrowserSync configuration, such as ghost mode settings. ```typescript { ghostMode: { clicks: false }, // other option changes } ``` -------------------------------- ### Example SVG Icon Usage Source: https://github.com/browsersync/browser-sync/blob/master/packages/browser-sync-ui/public/img/icons/preview.html Demonstrates how to embed an SVG icon using the `` and `` elements. This is the standard method for displaying icons from an SVG sprite. ```html ``` -------------------------------- ### BrowserSync Plugin Manager Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/index.md Demonstrates how to use the plugin manager to extend BrowserSync with custom plugins. Built-in plugins are listed for reference. ```javascript // Built-in plugins - logger: Logging - socket: Socket.IO - file:watcher: File watching - server: HTTP server - client:script: Client script injection - UI: Control panel // Can be extended with custom plugins browserSync.use('my-plugin', { plugin: fn }); ``` -------------------------------- ### Stream CSS Changes with BrowserSync and Gulp Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browsersync-core.md This example demonstrates how to use BrowserSync's stream() function within a Gulp pipeline to reload CSS files as they are compiled. ```javascript const browserSync = require('browser-sync'); const gulp = require('gulp'); const sass = require('gulp-sass'); browserSync.init({ server: true }); gulp.task('scss', function() { return gulp.src('src/**/*.scss') .pipe(sass()) .pipe(gulp.dest('dist/css')) .pipe(browserSync.stream({ match: '**/*.css' })); }); ``` -------------------------------- ### Configure Serve-Static Middleware Options Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Customize the behavior of the `serve-static` middleware, such as setting file extensions to prioritize or cache control. ```javascript { serveStaticOptions: { extensions: ['html', 'htm', 'xhtml'], maxAge: '1d', dotfiles: 'allow' } } ``` -------------------------------- ### Programmatic BrowserSync Initialization Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/index.md This JavaScript snippet demonstrates how to create and initialize a BrowserSync instance programmatically. It allows for custom server configurations, port selection, and watching files for automatic reloads. ```javascript const browserSync = require('browser-sync'); const instance = browserSync.create('dev'); instance.init({ server: 'dist', port: 3000, notify: true }, (err, bs) => { instance.watch('dist/**/*', (event, file) => { instance.reload(file); }); }); ``` -------------------------------- ### Accessing Plugins via Plugin Manager Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Demonstrates how to retrieve and interact with a registered plugin instance using the Plugin Manager after BrowserSync has been initialized. ```APIDOC ## Accessing Plugins via Plugin Manager ### Description Retrieve a plugin instance from the `pluginManager` after `browserSync.init()` has completed. This allows direct invocation of plugin methods. ### Method `browserSync.init(options, callback)` followed by `bs.pluginManager.get(pluginName)` ### Parameters #### `init` Callback Parameters - **err** (Error) - An error object if initialization fails. - **bs** (BrowserSyncInstance) - The BrowserSync instance. #### `pluginManager.get` Parameters - **pluginName** (string) - The registered name of the plugin. ### Request Example ```javascript const browserSync = require('browser-sync'); browserSync.init({ server: true }, (err, bs) => { const myPlugin = bs.pluginManager.get('my-plugin'); if (myPlugin) { myPlugin.doSomething(); } }); ``` ### Response #### Success Response - **myPlugin** (object | null) - The plugin instance if found, otherwise null. ``` -------------------------------- ### Retrieve BrowserSync Instance by Name Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browsersync-core.md Use the `get()` function to retrieve a previously initialized BrowserSync instance by its unique name. This is useful for interacting with a specific instance after it has been set up. ```javascript const browserSync = require('browser-sync'); // Initialize with a name browserSync.init({ server: true }, { name: 'dev' }, (err, bs) => { // Later, retrieve the instance const instance = browserSync.get('dev'); instance.reload(); }); ``` -------------------------------- ### Initialize Multiple BrowserSync UI Instances Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Create and initialize multiple BrowserSync instances, each with its own UI on a separate port. This is useful for managing different development environments simultaneously. ```javascript const bs1 = browserSync.create('dev'); const bs2 = browserSync.create('prod'); bs1.init({ ui: { port: 3001 } }); bs2.init({ ui: { port: 3002 } }); ``` -------------------------------- ### Register a one-time event listener Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/events.md Use `once` to register a callback that fires only on the first occurrence of an event. This is ideal for setup tasks that should only run once, like initial service initialization. ```typescript once(event: string, callback: Function): this ``` ```javascript bs.events.once('service:init', () => { console.log('First init only'); }); ``` -------------------------------- ### Configure BrowserSync with connect-history-api-fallback Source: https://github.com/browsersync/browser-sync/wiki/Browsersync-for-SPA Use this middleware configuration to enable BrowserSync to serve Single Page Applications. This setup ensures that all incoming requests are directed to the root of your SPA. ```javascript historyApiFallback = require('connect-history-api-fallback') server: { baseDir: "...", middleware: [ historyApiFallback() ] } ``` -------------------------------- ### Configure Custom File Extensions Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Provide an array of file extensions to the `extensions` option to serve them with custom types. ```javascript { extensions: ['html', 'css', 'js'] } ``` -------------------------------- ### BrowserSync Middleware with Dynamic Content Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/client-script-injection.md Example of creating BrowserSync middleware that includes dynamic content generated by functions and static strings. This is useful for injecting real-time or conditional script elements. ```javascript const browserSync = require('browser-sync-client'); const dynamicContent = [ browserSync.minified(), () => `console.log('Connected at ${new Date()}');`, '/* Custom config */' ]; const middleware = browserSync.middleware({}, dynamicContent); ``` -------------------------------- ### Initialize Plugins Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Initializes all plugins that have been registered with the BrowserSync instance. This is typically called automatically during BrowserSync startup. ```typescript init(): void ``` -------------------------------- ### Accessing and Using the Logger Plugin Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md How to retrieve the logger plugin instance and use its methods for output. ```javascript const logger = bs.pluginManager.get('logger'); logger.info('Message'); logger.error('Error message'); ``` -------------------------------- ### POST /api/options Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Updates BrowserSync configuration options. ```APIDOC ## POST /api/options ### Description Update BrowserSync options. ### Method POST ### Endpoint /api/options ### Request Body - **ghostMode** (object) - An object containing changes to ghost mode settings. For example, `{"clicks": false}`. - **other option changes** - Allows for updating other BrowserSync configuration options as needed. ### Request Example ```json { "ghostMode": { "clicks": false } // other option changes } ``` ``` -------------------------------- ### Applying Webfont in CSS Source: https://github.com/browsersync/browser-sync/blob/master/packages/browser-sync/test/fixtures/fonts/roboto/Roboto-Regular-demo.html This CSS example demonstrates how to apply a webfont to an HTML element by adding its 'font-family' name to the font stack. Ensure the 'font-family' name matches the one defined in your @font-face rule. ```css p { font-family: 'MyWebFont', Arial, sans-serif; } ``` -------------------------------- ### Access Plugin Instance via Plugin Manager Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/plugin-system.md Demonstrates how to retrieve a specific plugin instance from the BrowserSync Plugin Manager after initialization and call its methods. ```javascript const browserSync = require('browser-sync'); browserSync.init({ server: true }, (err, bs) => { // Get plugin instance const myPlugin = bs.pluginManager.get('my-plugin'); // Call plugin methods if (myPlugin) { myPlugin.doSomething(); } }); ``` -------------------------------- ### Configure Chokidar Watcher Options Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/configuration.md Provide Chokidar watcher configuration options. Defaults to `{ ignoreInitial: true }`. Options include `usePolling`, `depth`, and `ignorePermissionErrors`. ```javascript { watchOptions: { ignoreInitial: true, usePolling: false, depth: undefined, ignorePermissionErrors: false } } ``` -------------------------------- ### Configure Watch Options for Large Projects Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/file-watching.md Optimize file watching for projects with many files by setting a watch depth and ignoring large directories. Use file system watchers for better performance. ```javascript { watch: true, watchOptions: { usePolling: false, // File system watchers (faster) depth: 10, // Limit directory depth ignored: [ 'node_modules', 'dist', '.git' ] }, ignore: ['dist/**'] // Also ignored by reload logic } ``` -------------------------------- ### BrowserSync UI Plugin Configuration Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Configure the BrowserSync UI as a plugin. It initializes automatically when 'ui.port' is set and runs on a separate port from the main BrowserSync server. ```javascript module.exports["plugin:name"] = "BrowserSync UI"; ``` -------------------------------- ### BrowserSync UI Initialization Callback Source: https://github.com/browsersync/browser-sync/blob/master/_autodocs/api-reference/browser-sync-ui.md Set a callback function to be invoked when the UI server is ready. This allows for actions to be performed only after the UI has fully initialized. ```typescript ui.cb = callback || function() { /* noop */ }; ui.init(); // Triggers callback when ready ```