Browsersync 支持的参数

这些都是使用 Browsersync 时可以配置的参数。首先创建一个参数对象,并将其作为 第一个参数 (针对 GulpJS 和普通的 API 调用)传递给函数。如果你使用的是 Grunt,你仍然可以使用所有这些参数,但是你需要按照 Browsersync Grunt 文档 中的说明来使用。

  • 类型: Object

注意: 支持的最低版本为 2.0.0

Browsersync 包含了一个通过独立端口访问的用户界面。 通过用户界面可以控制所有设备、推送同步更新等。

// Change the default port
ui: {
    port: 8080
}

// Change the default weinre port
ui: {
    port: 8080,
    weinre: {
        port: 9090
    }
}

// Disable UI completely
ui: false
  • 类型: Array | String
  • 默认值: false

Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS & images) or will cause all browsers to do a full-page refresh.

// single file
browserSync({
    files: "app/css/style.css"
});

// multiple files
browserSync({
    files: ["app/css/style.css", "app/js/*.js"]
});

// patterns + 1 with custom callback
// since 2.6.0
browserSync({
    files: [
        "wp-content/themes/**/*.css",
        {
            match: ["wp-content/themes/**/*.php"],
            fn:    function (event, file) {
                /** Custom event handler **/
            }
        }
    ]
});
  • 类型: Array
  • 默认值: ["change"]

注意: 支持的最低版本为 2.18.8

Specify which file events to respond to. Available events: add, change, unlink, addDir, unlinkDir

  • 类型: Boolean
  • 默认值: false

注意: 支持的最低版本为 2.23.0

Watch files automatically - this should be used as an alternative to the files option. When this option is used, some directories will be ignored automatically such as node_modules bower_components .sass-cache .vscode .git .idea

var browserSync = require("browser-sync").create();

/**
 * This example will serve files from the './app' directory
 * and will automatically watch for html/css/js changes
 */
browserSync.init({
    watch: true,
    server: "./app"
});
  • 类型: Array
  • 默认值: []

注意: 支持的最低版本为 2.23.0

Patterns for any watchers to ignore. Anything provided here will end up inside watchOptions.ignored

  • 类型: Boolean
  • 默认值: false

注意: 支持的最低版本为 2.23.0

Serve an index.html file for all non-asset routes. Useful when using client-routers

  • 类型: Object
  • 默认值: undefined

注意: 支持的最低版本为 2.6.0

File watching options that get passed along to Chokidar. Check their docs for available options

const bs = require('browser-sync').create();

// Options passed to Chokidar
bs.init({
    watchOptions: {
        ignoreInitial: true,
        ignored: '*.txt'
    },
    files: ['./app']
});

// options for chokidar with custom callback
// since 2.6.0
bs.init({
    files: [
        {
            match: ["wp-content/themes/**/*.php"],
            fn: function (event, file) {
                /** Custom event handler **/
            },
            options: {
                ignored: '*.txt'
            }
        }
    ]
});

// NOTE: the .watch() method will not receive
// these options automatically, so you must provide
// them manually in the following way
bs.watch(['app/*.css'], {ignored: '*.map.css'});
  • 类型: Object | Boolean
  • 默认值: false

Use the built-in static server for basic HTML/JS/CSS websites.

// Serve files from the app directory
server: "app"

// Serve files from the current directory
server: true

// Serve files from the app directory with directory listing
server: {
    baseDir: "app",
    directory: true
}

// Multiple base directories
server: ["app", "dist"]

// Serve files from the app directory, with a specific index filename
server: {
    baseDir: "app",
    index: "index.htm"
}

// The static file server is based on expressjs/serve-static, 
// so we inherit all of their options, like trying a default extension
// when one isn't specified
// https://github.com/expressjs/serve-static
server: {
    baseDir: "app",
    serveStaticOptions: {
        extensions: ["html"]
    }
}

// Since version 1.2.1
// The key is the url to match
// The value is which folder to serve (relative to your current working directory)
server: {
    baseDir: "app",
    routes: {
        "/bower_components": "bower_components"
    }
}
  • 类型: String | Object | Boolean

Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site.

// Using a vhost-based url
proxy: "local.dev"

// Using a localhost address with a port
proxy: "localhost:8888"

// Using localhost sub directories
proxy: "localhost/site1"

// When your app also uses web sockets
// NOTE: requires 2.8.1 or above
proxy: {
    target: "http://yourlocal.dev",
    ws: true
}

proxy: {
    target: "http://yourlocal.dev",
}

// Modify the server request before it hits your application
// NOTE: requires v2.12.1
proxy: {
    target: "http://yourlocal.dev",
    proxyReq: [
        function(proxyReq) {
            proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
        }
    ]
}

// Modify the server response after it's returned from the proxy
proxy: {
    target: "http://yourlocal.dev",
    proxyRes: [
        function(proxyRes, req, res) {
            console.log(proxyRes.headers);
        }
    ]
}
  • 类型: Number
  • 默认值: 3000
// Use a specific port (instead of the one auto-detected by Browsersync)
port: 8080
  • 类型: Function | Array
  • 默认值: false
// Multiple Global Middlewares
middleware: [
    function (req, res, next) {
        /** First middleware handler **/
    },
    function (req, res, next) {
        /** Second middleware handler **/
    }
]

// Per-route middleware
// NOTE: requires v2.12.1
middleware: [
    {
        route: "/api",
        handle: function (req, res, next) {
            // handle any requests at /api
        }
    }
]

// Per-route + global middleware
// NOTE: requires v2.12.1
middleware: [
    require("compression")(), // global
    {
        route: "/api", // per-route
        handle: function (req, res, next) {
            // handle any requests at /api
        }
    }
]
  • 类型: Array
  • 默认值: []

注意: 支持的最低版本为 2.8.0

Add additional directories from which static files should be served. Should only be used in proxy or snippet mode.

var bs = require('browser-sync').create();

// Run in proxy mode with static files also served
// from current directory + ./app/css
bs.init({
    proxy: "http://www.bbc.co.uk",
    serveStatic: ['.', './app/css']
});

// Run in proxy mode where files under /assets will be served
// from a local ./tmp directory
// NOTE: requires 2.17.0
bs.init({
    proxy: "http://www.bbc.co.uk",
    serveStatic: [{
        route: '/assets',
        dir: 'tmp'
    }]
});

// Run in proxy mode where files under /assets + /content will be served
// from a local ./tmp directory
// NOTE: requires 2.17.0
bs.init({
    proxy: "http://www.bbc.co.uk",
    serveStatic: [{
        route: ['/assets', '/content'],
        dir: 'tmp'
    }]
});

// Run in proxy mode where files under /assets will be served
// from either the ./tmp or ./app directory
// NOTE: requires 2.17.0
bs.init({
    proxy: "http://www.bbc.co.uk",
    serveStatic: [{
        route: '/assets',
        dir: ['./tmp', './app']
    }]
});
  • 类型: Object
  • 默认值:

注意: 支持的最低版本为 2.17.0

Options that are passed to the serve-static middleware when you use the string[] syntax: eg: serveStatic: ['./app']. Please see serve-static for details

var bs = require('browser-sync').create();

// Serve files from 3 directories with serve-static options
bs.init({
    serveStatic: ['.', './app', './temp'],
    serveStaticOptions: {
        extensions: ['html'] // pretty urls
    }
});
  • 类型: Boolean
  • 默认值: undefined

注意: 支持的最低版本为 1.3.0

Enable https for localhost development. Note - this is not needed for proxy option as it will be inferred from your target url.

// Enable HTTPS for static file server
browserSync({
    server: "./app",
    https: true
});

// Enable HTTPS for snippet mode
browserSync({
    https: true
});

// Enable HTTPS mode with custom certificates
browserSync({
    server: "./app",
    https: {
        key: "path-to-custom.key",
        cert: "path-to-custom.crt"
    }
});
  • 类型: string
  • 默认值: undefined

注意: 支持的最低版本为 2.18.0

Override http module to allow using 3rd party server modules (such as http2) Note: these modules are not included in the Browsersync package - you need to 'npm install' any that you'd like to use.

// First run: npm install browser-sync http2
const bs = require('browser-sync').create();

bs.init({
    server: './app',
    httpModule: 'http2',
    https: true
});
  • 类型: String
  • 默认值:

注意: 支持的最低版本为 2.23.0

Current working directory

  • 类型: Object

Register callbacks via a regular option - this can be used to get access the Browsersync instance in situations where you cannot provide a callback via the normal API (for example, in a Gruntfile)

Note: Only the ready callback is currently supported here.

var browserSync = require("browser-sync").create();

browserSync.init({
    watch: true,
    server: "./app",
    callbacks: {
        /**
         * This 'ready' callback can be used
         * to access the Browsersync instance
         */
        ready: function(err, bs) {

            // example of accessing URLS
            console.log(bs.options.get('urls'));

            // example of adding a middleware at the end
            // of the stack after Browsersync is running
            bs.addMiddleware("*", function (req, res) {
                res.writeHead(302, {
                    location: "404.html"
                });
                res.end("Redirecting!");
            });
        }
    }
});
  • 类型: Object

Clicks, Scrolls & Form inputs on any device will be mirrored to all others.

// Here you can disable/enable each feature individually
ghostMode: {
    clicks: true,
    forms: true,
    scroll: false
}

// Or switch them all off in one go
ghostMode: false
  • 类型: String
  • 默认值: info

Can be either "info", "debug", "warn", or "silent"

// Show me additional info about the process
logLevel: "debug"

// Just show basic info
logLevel: "info"

// output NOTHING to the commandline
logLevel: "silent"
  • 类型: String
  • 默认值: Browsersync

注意: 支持的最低版本为 1.5.1

Change the console logging prefix. Useful if you're creating your own project based on Browsersync

logPrefix: "My Awesome Project"

// [My Awesome Project] Local URL: http://localhost:3000
// [My Awesome Project] Watching files....
// [My Awesome Project] File changed: "index.html"
  • 类型: Boolean
  • 默认值: false
// Log connections
logConnections: true

// Don't log connections
logConnections: false
  • 类型: Boolean
  • 默认值: true
// Log information about changed files
logFileChanges: true

// Don't log file changes
logFileChanges: false
  • 类型: : Boolean
  • 默认值: true

注意: 支持的最低版本为 1.5.2

Log the snippet to the console when you're in snippet mode (no proxy/server)

// Don't ever log the snippet
logSnippet: false
  • 类型: Object

注意: 支持的最低版本为 2.0.0

You can control how the snippet is injected onto each page via a custom regex + function. You can also provide patterns for certain urls that should be ignored from the snippet injection.

// Customise the placement of the snippet
// and ignore certain paths
snippetOptions: {

    // Ignore all HTML files within the templates folder
    ignorePaths: "templates/*.html",

    // Provide a custom Regex for inserting the snippet.
    rule: {
        match: /<\/body>/i,
        fn: function (snippet, match) {
            return snippet + match;
        }
    }
}
  • 类型: Array
  • 默认值: false

注意: 支持的最低版本为 2.4.0

Add additional HTML rewriting rules.

// Replace every occurrence of the word Browsersync with 'kittenz'
rewriteRules: [
    {
        match: /Browsersync/g,
        fn: function (req, res, match) {
            return 'kittenz';
        }
    }
]

// Also accepts a string as a replacement
rewriteRules: [
    {
        match: /(cats|kitten[sz]) are mediocre/g,
        replace: "$1 are excellent"
    }
]
  • 类型: String | Boolean
  • 默认值: null
// Tunnel the Browsersync server through a random Public URL
// -> http://randomstring23232.localtunnel.me
tunnel: true

// Attempt to use the URL "http://my-private-site.localtunnel.me"
tunnel: "my-private-site"
  • 类型: Boolean
  • 默认值: undefined

Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're working offline, you can reduce start-up time by setting this option to false

// Will not attempt to determine your network status, assumes you're ONLINE.
online: true

// Will not attempt to determine your network status, assumes you're OFFLINE
online: false
  • 类型: Boolean | String
  • 默认值: true

Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. Can be true, local, external, ui, ui-external, tunnel or false

// Stop the browser from automatically opening
open: false

// Open the localhost URL
open: "local"

// Open the external URL - must be online.
open: "external"

// Open the UI - since 2.0.0
open: "ui"

// Open the tunnel URL - must also set the `tunnel` option
open: "tunnel"
  • 类型: String | Array
  • 默认值: default
// Open the site in Chrome
browser: "google chrome"

// Open the site in Chrome & Firefox
browser: ["google chrome", "firefox"]
  • 类型: boolean
  • 默认值: false

注意: 支持的最低版本为 2.16.0

Add HTTP access control (CORS) headers to assets served by Browsersync.

  • 类型: Boolean
  • 默认值: false

Requires an internet connection - useful for services such as Typekit as it allows you to configure domains such as *.xip.io in your kit settings

// Append '.xip.io' to the hostname. (eg: http://192.168.0.4.xip.io:3002)
xip: true
  • 类型: Boolean
  • 默认值: false

Reload each browser when Browsersync is restarted.

// don't auto-reload all browsers following a Browsersync reload
reloadOnRestart: false
  • 类型: Boolean
  • 默认值: true

The small pop-over notifications in the browser are not always needed/wanted.

// Don't show any notifications in the browser.
notify: false
  • 类型: Boolean
  • 默认值: true
scrollProportionally: false // Sync viewports to TOP position
  • 类型: Number
  • 默认值: 0
scrollThrottle: 100 // only send scroll events every 100 milliseconds
  • 类型: String
  • 默认值: 'window.name'

Decide which technique should be used to restore scroll position following a reload. Can be window.name or cookie

  • 类型: Array
  • 默认值: []

注意: 支持的最低版本为 2.9.0

Sync the scroll position of any element on the page. Add any amount of CSS selectors

// Sync the scrollTop position of the element .scroller
// in addition to the window scroll
scrollElements: ['.scroller']
  • 类型: Array
  • 默认值: []

注意: 支持的最低版本为 2.9.0

Sync the scroll position of any element on the page - where any scrolled element will cause all others to match scroll position. This is helpful when a breakpoint alters which element is actually scrolling

// Sync the scrollTop position between different elements
// useful if your scroll container changes based on a breakpoint
scrollElementMapping: ['.scroller-mobile', '.scroller']
  • 类型: Number
  • 默认值: 0

Time, in milliseconds, to wait before instructing the browser to reload/inject following a file change event

// Wait for 2 seconds before any browsers should try to inject/reload a file.
reloadDelay: 2000
  • 类型: Number
  • 默认值: 0

注意: 支持的最低版本为 2.6.0

Wait for a specified window of event-silence before sending any reload events.

// Wait 2 seconds after a reload event before allowing more.
reloadDebounce: 2000
  • 类型: Number
  • 默认值: 0

注意: 支持的最低版本为 2.13.0

Emit only the first event during sequential time windows of a specified duration.

  • 类型: Array
  • 默认值: []

注意: 支持的最低版本为 2.6.0

User provided plugins

// First run `npm install bs-html-injector`
// Then provide the module name
plugins: ["bs-html-injector"]

// If the plugin you are using requires options
// just as bs-snippet-injector requires a 'file' option,
// you can pass an object instead like this.
plugins: [
    {
        module: "bs-snippet-injector",
        options: {
            file: "./app/index.php"
        }
    }
]

// Shorthand for bs-html-injector + files: ["*.html"] option
// NOTE: requires v2.12.1
plugins: ["bs-html-injector?files[]=*.html"]
  • 类型: Boolean
  • 默认值: true
// Inject CSS changes
injectChanges: true,

// Don't try to inject, just do a page refresh
injectChanges: false,
  • 类型: String | Null
  • 默认值: null
// Open the first browser window at URL + "/info.php"
startPath: "/info.php"
  • 类型: Boolean
  • 默认值: true

Whether to minify client script, or not.

// Don't minify the client-side JS
minify: false
  • 类型: String
  • 默认值: null
// Override host detection if you know the correct IP to use
host: "192.168.1.1"
  • 类型: String
  • 默认值: undefined

Specify a host to listen on. Use this if you want to prevent binding to all interfaces.

Note: When you specify this option, it overrides the 'host' option

  • 类型: Boolean
  • 默认值: false

注意: 支持的最低版本为 2.14.0

Support environments where dynamic hostnames are not required (ie: electron)

// For use in electron development
const bs = require('browser-sync');
bs.init({
    localOnly: true
});
  • 类型: Boolean
  • 默认值: true
// Don't send any file-change events to browsers
codeSync: false
  • 类型: Boolean
  • 默认值: true
// Don't append timestamps to injected files
timestamps: false
  • 类型: Function
  • 默认值: undefined

注意: 支持的最低版本为 1.5.0

Alter the script path for complete control over where the Browsersync Javascript is served from. Whatever you return from this function will be used as the script path.

// This will result in something like
// http://localhost:3002/browser-sync/browser-sync-client.1.6.0.js
scriptPath: function (path, port, options) {
    return options.getIn(['urls', 'local']) + path;
}
  • 类型: Object

注意: 支持的最低版本为 1.6.2

Configure the Socket.IO path and namespace & domain to avoid collisions.

// To change the namespace used by Browsersync
socket: {
    namespace: '/someothername'
}

// By default, Browsersync is configured to use the domain
// of your page in order to connect to socket.io
// eg: location.host + '/browser-sync
// but, should you need to change that, provide the `domain` property
socket: {
    domain: 'localhost:3000'
}
  • 类型: Object

注意: 支持的最低版本为 2.14.0

Configure the script domain