Skip to content

Instantly share code, notes, and snippets.

@rw3iss
Last active April 11, 2021 01:35
Show Gist options
  • Save rw3iss/b4a5be190d8daf0c8dcd5ef1fb950c8f to your computer and use it in GitHub Desktop.
Save rw3iss/b4a5be190d8daf0c8dcd5ef1fb950c8f to your computer and use it in GitHub Desktop.
browsersync script to hot reload any client project
const bs = require('browser-sync').create();
const url = require('url');
const fs = require('fs');
const path = require('path');
const PORT = 3300
const OUTPUT_DIR = './build'
const DEFAULT_FILE = "index.html"
bs.watch(`${OUTPUT_DIR}/**/*.js`, function (event, file) {
bs.reload('*.js')
})
bs.watch(`${OUTPUT_DIR}/**/*.css`, function (event, file) {
if (event === 'change') {
bs.reload('*.css')
}
})
bs.init({
port: PORT,
server: OUTPUT_DIR,
serveStatic: [`${OUTPUT_DIR}/static/`],
//cors: true,
browser: "google chrome", // [ "google chrome", "firefox"]
open: "local", // false
reloadOnRestart: true,
ui: false,
notify: false,
middleware: function(req, res, next) {
// this redirects all non-asset urls to the root index.html file, for development purposes
if (req.url.match(/^(.*)(.css|.js|.ttf|.png|.jpg)/)) {
return next();
}
var fileName = url.parse(req.url);
fileName = fileName.href.split(fileName.search).join("");
var fileExists = fs.existsSync(path.resolve(__dirname, "../") + fileName);
if (!fileExists && fileName.indexOf("browser-sync-client") < 0) {
req.url = "/" + DEFAULT_FILE;
}
return next();
}
//scrollProportionally: false
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment