Reputation: 3
In Fastify framework is there anyway to reflesh the browser when changes happen on save.
In Express we have npm livereload
as a middleware to listen to backend changes in Express. Are there any similar functions in Fastify or do I have to write my own registered plugin to automatically reflesh the browser on backend changes?
Upvotes: 0
Views: 3428
Reputation: 3816
The livereload
package that you mentioned is a general-purpose tool that works with Fastify as well. I was able to make it run with the following packages:
tsc -w -outdir dist/
to watch the .ts
files and transpile them into .js
filesnodemon -r dotenv/config dist/server.js
to watch the .js
files and restart the web serverlivereload ./dist/ -w 500
so that the browser refreshes once the server restartedpackage.json
"scripts": {
"build": "tsc",
"start": "node -r dotenv/config dist/server.js",
"dev:tsc": "tsc -w -outdir dist/",
"dev:watch": "nodemon -r dotenv/config dist/server.js",
"dev:livereload": "livereload ./dist/ -w 500",
"dev": "concurrently -k -p \"[{name}]\" -n \"TypeScript,App,LiveReload\" -c \"yellow.bold,cyan.bold,green.bold\" \"yarn dev:tsc\" \"yarn dev:watch\" \"yarn dev:livereload\" "
},
Note that you need to include the following
<script>
tag in your.html
files to make livereload work<script> document.write( '<script src="http://' + (location.host || "localhost").split(":")[0] + ':35729/livereload.js?snipver=1"></' + "script>" ); </script>
This was enough to make my small Fastify project run, your milage may vary.
Upvotes: 2
Reputation: 12880
Yes, there is the fastify-cli
module for that:
https://github.com/fastify/fastify-cli
it has the --watch
option that you can use to live reload your backend on file changes.
In your package.json
add this script:
"dev": "fastify start -l info --watch --pretty-logs app.js",
Note that app.js must expose this interface:
module.exports = function (fastify, ops, next) {
next()
}
Upvotes: 0