Watching Metalsmith

Don't use metalsmith-watch, it caused issues with various plugins. It is also good to separate the build process from watching (and triggering a re-build), the build shouldn't know anything except for what it is building.

To achieve this, use browser-sync and nodemon.

Nodemon is excellent at watching files and trigger something when they've changed.

Browser-sync is excellent at keeping the browser state and reloading when necessary.

Combined, they work together to watch your files, rebuild and reload the browser when needed.

package.json scripts section:

...
"main": "build.js",
"scripts": {
	...
	"dev": "npm run browser_sync & NODE_ENV=development nodemon --exec 'npm start && browser-sync reload'",
	"browser_sync": "browser-sync start --server site --browser=chrome",
	...
},
...
  • browser_sync starts browser-sync, serves ./site, starts chrome as the browser
  • dev starts browser_sync and nodemon watches the filesystem. When nodemon sees a change it will run the build script and reload the browser with the changes.

nodemon.json:

{
 "ignore": ["site/*", "node_modules/*", "assets/*", "modules/vendor/*"],
 "ext": "js, hbs, scss, md, html, yml",
 "no_delay": "200ms"
}
  • ignore is what to ignore
  • ext are the extensions to watch
  • no_delay waits for a 200ms before activating the . Useful for if you change a few files at once.

To watch the files npm run dev. Win!