Browsersync for a monorepo setup
When working with multiple webpack/gulp instances in a monorepo setup, handling live reload becomes a challenge. I decided to use BrowserSync with gulp to watch changes on all packages.
How it works?
I handle my monorepo with lerna, we are running browserSync using gulp and to run this at the same time, just add it as a "npm script", I called it npm start
and should look like this:
{
"name": "root",
"private": true,
"scripts": {
"start": "concurrently --kill-others \"npx lerna run start --parallel\" \"npx gulp --silent\"",
"postinstall": "npx lerna bootstrap"
},
"devDependencies": {
"browser-sync": "^2.26.7",
"concurrently": "^4.1.2",
"gulp": "^4.0.2",
"lerna": "^3.16.4"
},
"dependencies": {}
}
concurrently
will run both lerna and gulp "concurrently".
Once gulp runs, it's using browserSync to create a server and watch for changes in all "src" directories inside every package. You might use webpack/gulp,etc to build every package as long as you use the same structure and set the same script name on package.json
. For ex. If every package has a build
script, you would run them with lerna just like this: npx lerna run build
.
As soon as browserSync detects a change, it will run gulp.watch
to wait for changes in the dist
directory. If the change is "CSS" related (css preprocessors/files) it will inject the change in the browser, if it's not, it will do a hard reload. You can read the code right here
It's very flexible and easy to use. You can even use it for Wordpress. For example, every plugin/theme would behave as a "package" and you can add multiple directories to watch using the directories_to_watch
option inside the gulpfile.js to make it look like:
/
/plugins
plugin1
plugin2
/themes
/theme1
/theme2