Getting Browsersync running with Gulp 4 and Valet on macOS
Get Browsersync going with Gulp 4+ and Valet as a local development environment. With Gulp 4+ there has been some code upgrades that require any older gulp.js files to be updated, this guide looks at making Browsersync work with Gulp with the local development tool being Valet.
nodejs
Ensure you already have nodejs and npm installed, you can do this via Homebrew or a direct install from Node. Current stable long term version is 18. You can check your node version with …
node -v
Gulp
Next get Gulp installed, if you have an existing install check your versions…
gulp -v
You will see 2 versions if the path you are in already has an npm package.json file, Gulp 4+ has changed from previous versions.
CLI version: 2.2.0 Local version: 4.0.2
If you are missing either, you can install the CLI version with …
npm install --global gulp-cli
And your local package version should be added to a directory already with a package.json file, if not run npm init and then run…
npm install --save-dev gulp
Browsersync
Install Browsersync…
npm install browser-sync --save-dev
To update Browsersync globally run:
npm install -g browser-sync
package.json
Your package.json file should resemble this…
{ "name": "project_name", "version": "1.0.0", "description": "description", "repository": { "type": "git", "url": "?.git" }, "author": "author", "devDependencies": { "browser-sync": "^2.26.7", "gulp": "^4.0.2", } }
Create a gulp.js file
const gulp = require("gulp"); const browserSync = require("browser-sync").create(); const sitename = 'gulp'; // set your siteName here const username = 'neilg'; // set your macOS userName here function watch() { browserSync.init({ // proxy: sitename +'.test', // or if site is http comment out below block and uncomment line above proxy: 'https://' + sitename + '.test', host: sitename + '.test', open: 'external', port: 8000, https: { key: '/Users/' + username + '/.config/valet/Certificates/' + sitename + '.test.key', cert: '/Users/' + username + '/.config/valet/Certificates/' + sitename + '.test.crt', }, }); // Watched files paths gulp.watch('./*.php').on('change',browserSync.reload); gulp.watch('./js/*.js').on('change', browserSync.reload); gulp.watch('./css/*.css').on('change', browserSync.reload); gulp.watch('./*css').on('change', browserSync.reload); } exports.default = watch;
Set the username and site name variables, choose either http v https for the browser reload and update any paths you need watched.
I have found some issues with regular http sites reloading with macOS Catalina so I make all sites with https with…
wp valet secure <sitename>
Run gulp
Now from within the project directory you can run the default gulp task…
gulp
Now browsersync will reload on any file changes.
Please note the server is set up as proxy to place nicely with Valet – if you are not using Valet or a similar local dev but instead a server app like set up see the browsersync docs.