Автоматическое обновление страницы с помощью browser-sync для gulp

Живая перезагрузка с gulp-browserSync

BrowserSync является вероятно одним из самых полезных плагинов, который хотелось бы иметь разработчику. Он на деле даёт вам возможность запустить сервер, на котором вы можете выполнять свои приложения. Он заботится о перезагрузке ваших HTML/PHP-файлов. У него также есть возможность обновить/внедрить CSS и JavaScript-файлы в HTML и многое другое. С помощью этого плагина вы идёте исключительно вперёд.


Теперь посмотрим, как это работает. Перейдите в папку проекта и установите плагин browser-sync так:

Включите его в файл gulpfile.js:

Функция перезагрузки BrowserSync называется reload(). Давайте вызовем её и сохраним в переменной, просто для понятности.

Обратите внимание, что там, где я использую reload() вы также можете использовать browserSync.reload(). Задайте переменную paths вроде этого:

Задайте переменную paths вроде этого:

Эти файлы мы отслеживаем на любые изменения.

Мы создали задачу для файлов Sass и JavaScript, теперь давайте добавим одну для HTML-файлов.

Всё что делает эта задача — пропускает наш HTML-файл через функцию reload() из browser-sync. Если вы, к примеру, используете jade то могли бы компилировать его до перезагрузки.

Делаем то же самое с нашими существующими задачами:

browser-sync нужно знать расположение файлов, которые мы перезагружаем/синхронизируем и запустить мини-сервер основанный на этом; порт для прослушивания; прокси, если возможно и др. Посмотрите все варианты здесь.

Давайте настроим browser-sync и предоставим ему всю информацию.

Обратите внимание, что если вы не указали точный номер порта, browser-sync будет использовать порт 3000 по умолчанию. Теперь добавьте эту задачу в задачу watcher:

Теперь добавьте эту задачу в задачу watcher:

И, наконец, подретушируем задачу default:

Окончательно файл gulpfile.js должен выглядеть следующим образом:

После этого перейдите в папку проекта, если вы ещё не там, и запустите gulp. Сделайте несколько изменений в HTML или Sass-файле и наблюдайте магию Gulp! Если всё пойдёт хорошо, в консоли у вас должно быть что-то вроде следующего.

Context matching

  • path matching

    • — matches any path, all requests will be proxied.
    • — matches any path, all requests will be proxied.
    • — matches paths starting with
  • multiple path matching

    createProxyMiddleware([‘/api’, ‘/ajax’, ‘/someotherpath’], {…})

  • wildcard path matching

    • matches any path, all requests will be proxied.
    • matches any path which ends with
    • matches paths directly under path-absolute
    • matches requests ending with in the path of
    • combine multiple patterns
    • exclusion

    Note: In multiple path matching, you cannot use string paths and wildcard paths together.

  • custom matching

    For full control you can provide a custom function to determine which requests should be proxied or not.

    /**
     * @return {Boolean}
     */
    const filter = function (pathname, req) {
      return pathname.match('^/api') && req.method === 'GET';
    };
    
    const apiProxy = createProxyMiddleware(filter, {
      target: 'http://www.example.org',
    });

Sync Browser Mocks

Synchronous browser mocks for common async browser apis: , , , ,

These mocks make it dramatically easier to write tests for browser-based code, by making the above utilities synchronous. This way, you can write synchronous tests without having to care about timeouts, race conditions, and tests which pass sometimes and fail other times because some async api did not return on time.

require('sync-browser-mocks').patchAll();
require('sync-browser-mocks').patchPromise();

No additional changes are needed to use synchronous Promises: as soon as your promise is resolved, rather than waiting for the next tick, your and handlers will be immediately invoked.

var x =newPromise(function(resolve){resolve('foobar');});x.then(function(){console.log('This will be logged first');});console.log('This will be logged second');

Obviously, this relies on your code not containing any race conditions where you explicitly rely on being called on the next tick. These situations might break if you’re using synchronous promises — but that’s a good thing, as they should be factored out.

require('sync-browser-mocks').patchSetTimeout();

Any time you want to flush any pending timeout functions, you will need to call . For example:

setTimeout(function(){console.log('This will be logged second');},200);setTimeout(function(){console.log('This will be logged first');},100);setTimeout.flush();
require('sync-browser-mocks').patchSetInterval();

Any time you want to flush any pending interval functions, you will need to call . For example:

setInterval(function(){console.log('This will be logged second');},200);setInterval(function(){console.log('This will be logged first');},100);setInterval.cycle();setInterval.cycle();
require('sync-browser-mocks').patchXmlHttpRequest();

This module sets up a mock http backend you can use to handle incoming ajax requests:

var $mockEndpoint =require('sync-browser-mocks').$mockEndpoint;$mockEndpoint.register({    method'GET',    uri'/api/user/.+',    data{        name'Zippy the Pinhead'}}).listen();

Dynamic handler:

$mockEndpoint.register({    method'GET',    uri'/api/user/.+',handlerfunction(){return{            name'Zippy the Pinhead'};}}).listen();

Expecting calls in a test:

var $mockEndpoint =require('sync-browser-mocks').$mockEndpoint;var myListener =$mockEndpoint.register({    method'GET',    uri'/api/user/.+',    data{        name'Zippy the Pinhead'}});it('should correctly call /api/user',function(){myListener.expectCalls();myListener.done();});

All available options for use in config file

NOTE: not supported here, try to use something else like instead if you need to.

Server should only be used for static HTML, CSS & JS files. It should NOT be used if you have an existing PHP, WordPress, Rails setup. That’s what the proxy above is for.

Browser-sync will detect up to 3 available ports to use within a fixed range. You can override this if you need to.

Browser-sync will flash a quick message in all connected browsers to confirm that CSS injection has taken place (useful when you’re not sure whether the injection worked, or whether your CSS didn’t make a difference)

Save this as

Save this as

Now you can use it by calling it from the command-line

Fork this repo, clone it and then run

Tests are split into two categories: Client & Server

Client-side tests Client-side tests are located in test/client-script/*

// Run the client-side tests & exit

// Run the client-side tests & re-run on every file-change.

Server-side tests Server-side tests are located in test/new-server

// Run the server-side tests & exit

// Run the server-side tests & re-run on every file-change.

// Run the server-side tests & client-side tests once & exit.

This is a brand new project so expect bugs & be sure to report them.

Конфигурация gulp

Настройка сборщика осуществляется через файл gulpfile.js, который необходимо создать в корне проекта.

Подключим все зависимости:

gulpfile.js

JavaScript

const gulp = require(‘gulp’), pug = require(‘gulp-pug’), browserSync = require(‘browser-sync’);

const reload = browserSync.reload;

1 2 3 4 5 6 7

constgulp=require(‘gulp’),

pug=require(‘gulp-pug’),

browserSync=require(‘browser-sync’);

constreload=browserSync.reload;

 

Отдельно выносим функцию reload объекта browserSync, потому что мы будем ей часто пользоваться.

Напишем gulp-таск для транспиляции pug-кода в html:

JavaScript

gulp.task(‘pug’, function() { gulp.src(‘./pug/index.pug’) .pipe(pug({ pretty: true })) .pipe(gulp.dest(‘./dist’)) });

1 2 3 4 5 6 7

gulp.task(‘pug’,function(){

gulp.src(‘./pug/index.pug’)

.pipe(pug({prettytrue}))

.pipe(gulp.dest(‘./dist’))

});

 

Теперь добавим наблюдатель, который будет отслеживать изменения всех pug-файлов и обновлять транспилированный код:

JavaScript

gulp.task(‘watcher’, function() { gulp.watch(‘./pug/**/*.pug’, (event, sb) => { gulp.start(‘pug’); }); });

1 2 3 4 5 6 7

gulp.task(‘watcher’,function(){

gulp.watch(‘./pug/**/*.pug’,(event,sb)=>{

gulp.start(‘pug’);

});

});

 

Теперь, запустив оба таска по очереди, можно вручную обновлять браузер и сразу видеть изменения:

PowerShell

gulp pug gulp watcher

1 2 3 4

gulp pug

gulp watcher

 

Но это неудобно, давайте прикрутим синхронизацию с браузером.

Abstraction Layers


Syncs provides four abstraction layer over its real-time functionality for developers.

Developers can send messages using method of instance to send message to the server.Also all incoming messages are catchable using .

io.onConnection(client=>{io.send({text"im ready"});})
io.onMessage(message=>{alert(message.text);})

With a Publish and Subscribe solution developers normally subscribe to data using a string identifier. This is normally called a Channel, Topic or Subject.

io.publish('mouse-move-event',{xxLocation,yyLocation});
io.subscribe('weather-update',updates=>{});

### 3. Shared Data Abstraction Layer Syncs provides Shared Data functionality in form of variable sharing. Shared variables can be accessible in tree level: Global Level, Group Level and Client Level. Only Client Level shared data can be write able with client.

To get Client Level shared object use method of instance.

let info=io.shared('info');info.title="Syncs is cool!"

To get Group Level shared object use method of instance. First parameter is group name and second one is shared object name.

let info=io.groupShared('vips','info');document.title=info.onlineUsers+" vip member are online";

To get Global Level shared object use method of instance.

let settings=io.globalShared('settings');applyBackground(settings.background);

It’s possible to watch changes in shared object by using shared object as a function.

info((event)=>{document.title=info.title});

The callback function has two argument.

  • : an object that contains names of changed properties and new values.
  • a string variable with two value ( and ) which shows who changed these properties.

With help of RMI developers can call and pass argument to remote function and make it easy to develop robust and web developed application. RMI may abstract things away too much and developers might forget that they are making calls over the wire.

Before calling remote method from server ,developer should declare the function on client script.

object in instance is the place to declare functions.

io.functions.showMessage=function(message){alert(message);}

To call remote method on server use object.

io.remote.setLocation(latitude,longitude)

The remote side can return a result (direct value or Promise object) which is accessible using object returned by caller side.

io.functions.askName=function(title){returnprompt(title);}
io.functions.startQuiz=function(questions,quizTime){returnnewPromise((res,rej)=>{setTimeout(()=>{res(quizResult);},quizTime);})}
io.remote.getWeather(cityName).then(forcast=>{})

How to use it

Browser-sync is a command-line tool & the from the command above makes it available everywhere on your system. Just into your website and run one of the commands below. If any further instructions are needed, you’ll be notified on the command line.

Watch ALL CSS files in a directory for changes

Watch ALL CSS files & HTML files in a directory for changes

Using a local.dev vhost

Using a local.dev vhost with PORT

Using a an IP based host

Watch ALL CSS files for changes with a static server

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app»

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app» & specify the index file (note the missing l)

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app» & with ghostMode disabled

If you want to, you can provide a config file instead of having to remember all of the commands above. Also, a config file allows you to be more specific with options. Here’s an example of one that you would put in the root of your project.

Now, if you called the file , you’d simple run

Browser-sync и PHP-файлы

Измените файл index.html на index.php и подправьте пути так:

Это предполагает, что вы хотите работать с PHP, а не только с HTML. Перейдите к командной строке, остановите текущий процесс через Ctrl + C, а затем запустите gulp снова.

Gulp выполнит ваше приложение на http://localhost:8080, но вы увидите только это на странице:

Помните, перед выполнением любых инструкций PHP, вам нужен сервер PHP. Так что через эту ошибку Gulp пытается сказать нам, что никакого PHP-сервера не найдено.

Всё, что нам нужно сейчас сделать — это запустить сервер PHP вместе с нашими задачами. Для этого мы используем плагин gulp-connect-php.

Features of BrowserSync

Table of Contents

  • Live reloading: This is probably the most important feature of BrowserSync. change your code and the page is auto-reloaded. Live reloading works across many browsers and devices.
  • Interaction synchronization: It means that all your actions are mirrored across every browser. This little feature is useful for testing, especially, when testing across many devices. You can also customize what actions are mirrored across browsers.
  • Simulate slower connections: I believe you are expecting users from all over the world, and some countries are not fortunate enough to have fast internet connection; BrowserSync has a feature that you can use to throttle your website connection speed.
  • URL history: BrowserSync logs all browsing history so you can push a test URL to all devices.
  • Extra: BrowserSync is compatible with many task runners like GULP and Grunt. And they work across many operating systems.

All available options for use in config file

NOTE: not supported here, try to use something else like instead if you need to.

Server should only be used for static HTML, CSS & JS files. It should NOT be used if you have an existing PHP, WordPress, Rails setup. That’s what the proxy above is for.

Browser-sync will detect up to 3 available ports to use within a fixed range. You can override this if you need to.

Browser-sync will flash a quick message in all connected browsers to confirm that CSS injection has taken place (useful when you’re not sure whether the injection worked, or whether your CSS didn’t make a difference)

Save this as

Save this as

Now you can use it by calling it from the command-line

Fork this repo, clone it and then run

Tests are split into two categories: Client & Server

Client-side tests Client-side tests are located in test/client-script/*

// Run the client-side tests & exit

// Run the client-side tests & re-run on every file-change.

Server-side tests Server-side tests are located in test/new-server

// Run the server-side tests & exit

// Run the server-side tests & re-run on every file-change.

// Run the server-side tests & client-side tests once & exit.

This is a brand new project so expect bugs & be sure to report them.

Browsersync recipes.

There are endless amounts of possible integrations and workflow scenarios when using Browsersync, so this project is an attempt to highlight as many of them as we can, whilst providing full, working examples.

Here’s what we have currently…

  • Grunt, SASS, HTML/CSS injection example
  • Grunt & SASS
  • Grunt, SASS & Autoprefixer
  • Browserify, Babelify + Watchify + Sourcemaps Example
  • Gulp, SASS + Pug Templates
  • Gulp & Ruby SASS
  • Gulp & SASS
  • Gulp & Swig Templates
  • Gulp, SASS + Slow running tasks
  • HTML/CSS injection example
  • Middleware + CSS example
  • Proxy example + injecting custom css file
  • Server example
  • Server with pre-gzipped assets example
  • Server includes example
  • Server + Logging + History API fallback middlewares Example
  • Combine node-sass and postcss with BS.
  • Webpack + Babel
  • Webpack + Monkey Hot Loader
  • Webpack + Preact Hot Loader
  • Webpack + React Hot Loader
  • Webpack + React Transform HMR
  • Webpack + TypeScript
  • Webpack, TypeScript + React

… each one is a full, working example — just have a look at the in each one for installation instructions.

Contributions / Feedback

Spotted an error? Couldn’t get one of the examples running? Have your own sweet setup that you want to show off to the world? We’d love to receive your feedback and contributions — so please get in touch! We aim to make this project the canonical source of example projects & code snippets related to running Browsersync.

How to contribute an example

First thing you should do, is take a look at our simplest example here — this will give you a great head-start on setting up your code.

Then, this repo and your fork down to your local machine. Now create a new folder inside (note the naming structure). This is where you create your awesome example. You’re free to do as you like, but there are a couple of rules you’ll need to follow to ensure the project can build.

Required Files

  • (see below for requirements)
  • (or any JS file showing the example)
  • directory. Always include the minimum HTML, JS & CSS needed to prove your example.

Do NOT include

  • (this is created dynamically for you)
  • any other files that are not related to your example.

package.json requirements

start command: For consistency, ensure your example can be run with the command . To do this, you just need to provide something along these lines:

"scripts": {
    "start": "node app.js"
},

main file: We inline your main Javascript file into the , so don’t miss this field.

"main": "app.js" // or gulpfile.js etc

description: We use this as the Title. So make it short and descriptive, such as

"description": "Server example"

All available options for use in config file

NOTE: not supported here, try to use something else like instead if you need to.

Server should only be used for static HTML, CSS & JS files. It should NOT be used if you have an existing PHP, WordPress, Rails setup. That’s what the proxy above is for.

Browser-sync will detect up to 3 available ports to use within a fixed range. You can override this if you need to.

Browser-sync will flash a quick message in all connected browsers to confirm that CSS injection has taken place (useful when you’re not sure whether the injection worked, or whether your CSS didn’t make a difference)

Save this as

Save this as

Now you can use it by calling it from the command-line

Fork this repo, clone it and then run

Tests are split into two categories: Client & Server

Client-side tests Client-side tests are located in test/client-script/*

// Run the client-side tests & exit

// Run the client-side tests & re-run on every file-change.

Server-side tests Server-side tests are located in test/new-server


// Run the server-side tests & exit

// Run the server-side tests & re-run on every file-change.

// Run the server-side tests & client-side tests once & exit.

This is a brand new project so expect bugs & be sure to report them.

Proxy Mode

Without opening a folder

The image below is a Laravel web application hosted on a docker machine, the guideline don’t just applies for Laravel, this also applied for other web application.

  1. Type command on any kind of file:
  2. Type in the URL of the original website, e.g. , or

With opening a folder

  1. Type command on any kind of file:
  2. Type in the URL of the original website, e.g. , or
  3. Type the path of files you want to watch relative to the root folder

Refresh Side Panel

Run command which acts like F5 in browser to refresh the side panel

Sometimes the page may crash and no tag is returned, then the script of the browser sync cannot be injected and the codeSync will stop. In this situation,

All available options for use in config file

NOTE: not supported here, try to use something else like instead if you need to.

Server should only be used for static HTML, CSS & JS files. It should NOT be used if you have an existing PHP, WordPress, Rails setup. That’s what the proxy above is for.

Browser-sync will detect up to 3 available ports to use within a fixed range. You can override this if you need to.

Browser-sync will flash a quick message in all connected browsers to confirm that CSS injection has taken place (useful when you’re not sure whether the injection worked, or whether your CSS didn’t make a difference)

Save this as

Save this as

Now you can use it by calling it from the command-line

Fork this repo, clone it and then run

Tests are split into two categories: Client & Server

Client-side tests Client-side tests are located in test/client-script/*

// Run the client-side tests & exit

// Run the client-side tests & re-run on every file-change.

Server-side tests Server-side tests are located in test/new-server

// Run the server-side tests & exit

// Run the server-side tests & re-run on every file-change.

// Run the server-side tests & client-side tests once & exit.

This is a brand new project so expect bugs & be sure to report them.

Активация browser-sync

Модуль browser-sync нужно инициализировать, а затем вызывать метод перезагрузки в нужных местах.

Таск инициализации выглядит примерно так:

PowerShell

gulp.task(‘browser-sync’, function() { browserSync.init({ server: { baseDir: ‘./dist’ } }) });

1 2 3 4 5 6 7 8 9

gulp.task(‘browser-sync’,function(){

browserSync.init({

server{

baseDir’./dist’

}

})

});

 

У модуля много настроек, их можно посмотреть на его странице на npmjs.

Если из консоли мы вызовем этот таск на выполнение, в браузере автоматически откроется страница ./dist/index.html.

Теперь добавим перезагрузку к задаче pug:

JavaScript

gulp.task(‘pug’, function() { gulp.src(‘./pug/index.pug’) .pipe(pug({ pretty: true })) .pipe(gulp.dest(‘./dist’)) .pipe(reload({ stream: true })) });

1 2 3 4

6 7 8

 

gulp.task(‘pug’,function(){

gulp.src(‘./pug/index.pug’)

.pipe(pug({prettytrue}))

.pipe(reload({streamtrue}))

});

 

И создадим дефолтный таск, который будет запускать все задачи в правильном порядке:

JavaScript

gulp.task(‘default’, );

1 2 3

gulp.task(‘default’,’watcher’,’browser-sync’,’pug’);

 

Примерно такой gulpconfig.js я использую для верстки простых лендингов. Он позволяет удобно использовать простые шаблонизаторы, процессоры CSS и прочие полезные штуки без особых сложностей и сборок.

Using BrowserSync

First we will use BrowserSync with static files. Assuming you have a directory structure like:

And from the root of your project directory run the following command

This instructs BrowserSync to watch all HTML and CSS files. Once you run the command, a browser window opens in the default browser serving the directories root file, in this case . In the console of the running BrowserSync start command, you should see the following result.

Upgrade Your JS Go from vanilla JavaScript React

Watch for FREE

  • Local: represents the address on your local machine with which you can view the project.
  • External: represents the address that any user on you local network(LAN or wifi) can view the project.
  • UI: will be talked about below.

How to use it

Browser-sync is a command-line tool & the from the command above makes it available everywhere on your system. Just into your website and run one of the commands below. If any further instructions are needed, you’ll be notified on the command line.

Watch ALL CSS files in a directory for changes

Watch ALL CSS files & HTML files in a directory for changes

Using a local.dev vhost

Using a local.dev vhost with PORT

Using a an IP based host

Watch ALL CSS files for changes with a static server

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app»

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app» & specify the index file (note the missing l)

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app» & with ghostMode disabled

If you want to, you can provide a config file instead of having to remember all of the commands above. Also, a config file allows you to be more specific with options. Here’s an example of one that you would put in the root of your project.

Now, if you called the file , you’d simple run

Shorthand

Use the shorthand syntax when verbose configuration is not needed. The and will be automatically configured when shorthand is used. Options can still be used if needed.

createProxyMiddleware('http://www.example.org:8000/api');
// createProxyMiddleware('/api', {target: 'http://www.example.org:8000'});

createProxyMiddleware('http://www.example.org:8000/api/books/*/**.json');
// createProxyMiddleware('/api/books/*/**.json', {target: 'http://www.example.org:8000'});

createProxyMiddleware('http://www.example.org:8000/api', { changeOrigin: true });
// createProxyMiddleware('/api', {target: 'http://www.example.org:8000', changeOrigin: true});

app.use(path, proxy)

If you want to use the server’s parameter to match requests; Create and mount the proxy without the http-proxy-middleware parameter:

app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));

documentation:

  • connect:
  • polka:

How to use it

Browser-sync is a command-line tool & the from the command above makes it available everywhere on your system. Just into your website and run one of the commands below. If any further instructions are needed, you’ll be notified on the command line.

Watch ALL CSS files in a directory for changes

Watch ALL CSS files & HTML files in a directory for changes


Using a local.dev vhost

Using a local.dev vhost with PORT

Using a an IP based host

Watch ALL CSS files for changes with a static server

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app»

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app» & specify the index file (note the missing l)

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app» & with ghostMode disabled

If you want to, you can provide a config file instead of having to remember all of the commands above. Also, a config file allows you to be more specific with options. Here’s an example of one that you would put in the root of your project.

Now, if you called the file , you’d simple run

Core concept

Proxy middleware configuration.

createProxyMiddleware( config)

const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org' });
//                                    \____/   \_____________________________/
//                                      |                    |
//                                    context             options

// 'apiProxy' is now ready to be used as middleware in a server.
  • context: Determine which requests should be proxied to the target host. (more on )
  • options.target: target host to proxy to. (protocol + host)

(full list of )

createProxyMiddleware(uri )

// shorthand syntax for the example above:
const apiProxy = createProxyMiddleware('http://www.example.org/api');

More about the .

Initialization

There is three way to setup:

  1. Use CDN hosted file:
    <scriptsrc="https://cdn.jsdelivr.net/npm/syncs-browser@1"></script>
  2. On server side it’s possible to access client script from instance:
    app.get('/syncs.js',(req,res)=>{res.send(io.clientScript);})

After serving client script, developers should include it in html page and create an instance of class.

<!doctype html><html><head><metacharset="UTF-8"><scriptsrc="syncs.js"></script></head><body></body><script>let io=newSyncs();</script></html>

Client Script constructor has config parameter:

  • : WebSocket url begins with protocol. default value is which domain name will sets automatically.
  • : If is then the Syncs instance will not connect to server on creation. To connect manuly to server developers should call method. default value is .
  • : This config makes the connection presistent on connection drop. default value is .
  • : time to wait befor each reconnecting try. default value is .
  • : This parameter enables debug mode on client side. default value is .

BrowserSync and Gulp task-runner

Still one of the best task-runners available to the community. To set up a BrowserSync GULP task, we need to have GULP installed. To install GULP, just run the following command:

In the root of your project folder, create a file named . In that file create a gulp task named .

To trigger this command, from the terminal run

What this does is the same as the BrowserSync command we ran earlier. BrowserSync monitors the directory defined in and whenever we run the command, the page reloads.

You might have already setup a server somewhere on your computer, and you want to keep it that way; Like I mentioned earlier, BrowserSync can act as a proxy to an existing server. To do so just:

The option points to the server you want to make a proxy. If your server makes use of WebSockets, you need to tell BrowserSync to enable WebSockets.

NOTE: BrowserSync has more options than just server and proxy. Take a look at some of the other options.

All available options for use in config file

NOTE: not supported here, try to use something else like instead if you need to.

Server should only be used for static HTML, CSS & JS files. It should NOT be used if you have an existing PHP, WordPress, Rails setup. That’s what the proxy above is for.

Browser-sync will detect up to 3 available ports to use within a fixed range. You can override this if you need to.

Browser-sync will flash a quick message in all connected browsers to confirm that CSS injection has taken place (useful when you’re not sure whether the injection worked, or whether your CSS didn’t make a difference)

Save this as

Save this as

Now you can use it by calling it from the command-line

Fork this repo, clone it and then run

Tests are split into two categories: Client & Server

Client-side tests Client-side tests are located in test/client-script/*

// Run the client-side tests & exit

// Run the client-side tests & re-run on every file-change.

Server-side tests Server-side tests are located in test/new-server

// Run the server-side tests & exit

// Run the server-side tests & re-run on every file-change.

// Run the server-side tests & client-side tests once & exit.

This is a brand new project so expect bugs & be sure to report them.

How to use it

Browser-sync is a command-line tool & the from the command above makes it available everywhere on your system. Just into your website and run one of the commands below. If any further instructions are needed, you’ll be notified on the command line.

Watch ALL CSS files in a directory for changes

Watch ALL CSS files & HTML files in a directory for changes

Using a local.dev vhost

Using a local.dev vhost with PORT

Using a an IP based host

Watch ALL CSS files for changes with a static server

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app»

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app» & specify the index file (note the missing l)

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app» & with ghostMode disabled

If you want to, you can provide a config file instead of having to remember all of the commands above. Also, a config file allows you to be more specific with options. Here’s an example of one that you would put in the root of your project.

Now, if you called the file , you’d simple run

How to use it

Browser-sync is a command-line tool & the from the command above makes it available everywhere on your system. Just into your website and run one of the commands below. If any further instructions are needed, you’ll be notified on the command line.

Watch ALL CSS files in a directory for changes

Watch ALL CSS files & HTML files in a directory for changes

Using a local.dev vhost

Using a local.dev vhost with PORT

Using a an IP based host

Watch ALL CSS files for changes with a static server

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app»

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app» & specify the index file (note the missing l)

Watch ALL CSS files for changes with a static server & specify that the base dir should be «app» & with ghostMode disabled

If you want to, you can provide a config file instead of having to remember all of the commands above. Also, a config file allows you to be more specific with options. Here’s an example of one that you would put in the root of your project.

Now, if you called the file , you’d simple run


С этим читают