Browser Sync 1) serves the content, detects changes, refreshes the browser, and offers many customization's.
How to use it to develop with live reloading.
The reload will work:
It can also serve as cross-browser testing tool.
Browsersync works by injecting an asynchronous script tag (<script async>...</script>) right after the <body> tag during the initial request. In order for this to work properly the <body> tag must be present.
This added script uses WebSockets to be able to refresh the page on file change.
npm install -g browser-sync
# or
yarn global add browser-sync
browser-sync init
Config file created bs-config.js
To use it, in the same directory run: browser-sync start --config bs-config.js
Example:
module.exports = {
"ui": {
"port": 3001
},
"files": ["test/public/*", "src/browser/*"],
"server": ["test/public","src/browser","output"],
}
where:
cd yourProjectDirectory
browser-sync start --server --files "*.html, css/*.css, js/*.js"
[Browsersync] Access URLs:
--------------------------------------
Local: http://localhost:3000
External: http://172.23.220.49:3000
--------------------------------------
UI: http://localhost:3001
UI External: http://localhost:3001
--------------------------------------
[Browsersync] Serving files from: ./
[Browsersync] Watching files...
where:
Then when a file change, you see in the log:
[Browsersync] Reloading Browsers...
When using a configuration file, you can enable cors with the below server configuration
"server": {
baseDir: ["src/main/html"],
middleware: function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
}
},
"cors": true
BrowserSync can act as a gateway proxy to an existing server (ie serving php, java, python or any other dynamic pages)
The proxy option points to the server you want to make a proxy.
Example:
browser-sync start -p http://localhost:81/ --files "*.css, syntax/*.php, *.js" --ws --no-inject-changes
[Browsersync] Proxying: http://localhost:81
[Browsersync] Access URLs:
----------------------------------
Local: http://localhost:3000
External: http://10.0.75.1:3000
----------------------------------
UI: http://localhost:3001
UI External: http://localhost:3001
----------------------------------
[Browsersync] Watching files...
[Browsersync] Reloading Browsers...
If you want to add SSL without warning, you need to add the key and certificate via a configuration file. Example:
{
"https": {
"key": "D:\\cert\\key.pem",
"cert": "D:\\cert\\cert.pem"
},
"proxy": "https://localhost:5175",
"host": "member.eraldy.dev",
"open": "external"
}