BrowserSync

repository·master·Indexed 11 days ago

https://github.com/browsersync/browser-sync

A tool for keeping multiple browsers and devices in sync during website development via real-time updates, live reloading, and CSS injection. Includes a web-based UI (version 2.0.0+), a client-side script for synchronized interactions, and a CLI for managing server, proxy, and file-watching configurations.

Tokens
10.5K
Snippets
35
Records
58
Agent score
95%

What's inside BrowserSync

  1. Requirements for BrowserSync script injection

    master
    BrowserSync works by injecting an asynchronous script tag (<script async>...</script>) immediately after the <body> tag during the initial request. For this injection to succeed, your HTML must contain a <body> tag. If your project structure does not allow for this, you must provide a custom rule for the snippet using the snippetOptions configuration option.
  2. Accessing options when upgrading from 1.x to 2.x

    master

    In BrowserSync 2.x, options are stored in an immutable data structure. While the public API remains largely unchanged, you can no longer access nested options via standard object property notation (e.g., bs.options.urls.local). Instead, you must use the .getIn() method to retrieve nested values.

    // Old 1.x way (will not work in 2.x)
    browserSync({server: true}, function(err, bs) {
      console.log(bs.options.urls.local);
    });
    
    // New 2.x way
    browserSync({server: true}, function(err, bs) {
      console.log(bs.options.getIn(["urls", "local"]));
    });
  3. How the `files` option interacts with `server` and `serveStatic`

    master

    When using the watch option, BrowserSync automatically expands the files watch list to include paths defined in your server and serveStatic configurations. This ensures that changes to your served files trigger a reload.

    Specifically, the following paths are added to the files list:

    • Any string paths provided to serveStatic.
    • The baseDir property if server is configured as a Map.
    • The directory path if server is a string.
    • All strings in the list if server is an array of strings.
    • The current directory (.) if server is set to true.

    If watch is not enabled, these paths are not automatically added to the files option.

  4. Parse and merge BrowserSync CLI options

    master

    When using BrowserSync via the CLI, the engine processes input arguments by merging them with the defaultConfig. This process involves a series of internal transformations to resolve complex options like server settings, proxy configurations, ports, hostnames, and file watching patterns.

    Key transformations applied during the merge process include:

    • Server & Proxy: Resolving server options, proxy settings, ports, host, and scheme (http/https).
    • File Watching: Handling files (globs or objects), extensions, watch patterns, and applying default ignore patterns or .gitignore rules.
    • Ghost Mode: Configuring synchronized interactions (clicks, scrolls, forms).
    • UI & Middleware: Setting the uiPort, middleware, and namespace.
    • Pathing: Setting the startPath, cwd (current working directory), and resolving snippet include/ignore paths.
  5. Understand BrowserSync server modes

    master

    The BrowserSync server behavior is determined by the mode option and the presence of proxy or server configurations.

    • Snippet Mode: Triggered if no proxy or server options are provided. It uses a specialized snippet server to facilitate client-side injection.
    • Proxy Mode: Triggered if the proxy option is configured. BrowserSync acts as a middleware proxying requests to a target URL.
    • Static Server Mode: Triggered if the server option is configured (and no proxy is present). BrowserSync serves files directly from the specified directory.

    When running in server or snippet modes, BrowserSync logs the scheme (e.g., http or https) being used.

  6. Configure Middleware via multiple locations

    master

    BrowserSync allows you to define middleware in three different locations within your configuration object. The project automatically merges these into a single middleware list.

    Supported locations:

    1. Top-level: middleware
    2. Server-specific: server.middleware
    3. Proxy-specific: proxy.middleware

    If you provide a function, it is treated as a single middleware entry. If you provide a list, it is merged with existing middleware. This allows you to define global middleware or scope middleware specifically to your server or proxy setup.

  7. Extend the BrowserSync UI via plugin hooks

    master

    The browser-sync-ui package provides a set of hook interfaces that allow BrowserSync plugins to inject custom functionality, markup, and logic into the BrowserSync UI. When developing a plugin for the UI, you can provide data through several specific hook types to influence how the UI is rendered and how it behaves.

    Key hook types include:

    • client:js: Used to inject client-side JavaScript into the UI. This can be a string or an array of strings.
    • templates: Used to provide Angular-compatible templates. These are wrapped in <script type="text/ng-template" id="..."></script> tags.
    • markup: Used to provide controller markup for plugins.
    • elements: Used to register toggle-able UI elements.
    • page: Used to define new pages, routes, and configurations within the UI.
  8. Generate an example BrowserSync configuration file

    master

    BrowserSync can automatically generate a template configuration file in your current working directory. This file includes default options (excluding internal keys like excludedFileTypes, injectFileTypes, and snippetOptions) to help you get started with custom setups.

    Once the file is created, you can use it by pointing the CLI to the specific configuration file using the --config flag.

    # After generating the config file (e.g., bs-config.js)
    browser-sync start --config bs-config.js
  9. Configure Scroll Synchronization

    master

    Synchronize scroll positions across devices.

    • scrollProportionally: Whether to sync scroll position proportionally. Defaults to true.
    • scrollThrottle: Throttle for scroll events. Defaults to 0.
    • scrollRestoreTechnique: Method to restore scroll position after reload. Options: "window.name" (default) or "cookie".
    • scrollElements: Array of CSS selectors for specific elements to sync scroll position for.
    • scrollElementMapping: Array of mappings to sync scroll positions of different elements (useful for responsive breakpoints).