使用tiny-lr自动刷新页面

编辑完代码,前端页面就能够自动刷新是一件很酷的事,能够显著提升调试的效率。css

我来讲说本身使用自动刷新页面的几种状况,若是是 node 项目我会使用本身作的模块,一个是 koajs 的中间件 koa-liveload,另外一个是 connect 的中间件 liveload,在 express 项目里面使用。html

组件的详细用法请参考文档,这里只想说这样作的方便之处在于只须要 2~3 行代码就能够启用 liveload 功能,而不用写什么 grunt 或者 gulp 那种看起来头疼的代码。前端

但是若是项目不是 nodejs 就不太好办了,幸运的是 tiny-lr 还提供了 Makefile 脚本,不过我通常是用本身写的,由于引用的 Makefile 不容易理解,其实不过是作了两件事,一是启动服务:node

watch:
    @echo ... Starting server, running in background ...
    @echo ... Run: "make stop" to stop the server ...
    @tiny-lr &

二是变化时经过post请求通知前端页面,git

build: 
    //构建过程的代码
    @curl -X POST http://localhost:35729/changed -d '{ "files": "build.js" }'

若是你还须要监视文件变化的话,我我的推荐 rewatch 这个小工具,大概用法如此:github

rewatch index.js *.css -c "make build"

最后的 Makfile 大概是这样子的:web

build: components index.js template.html
    //构建前端项目
    @curl -X POST http://localhost:35729/changed -d '{ "files": "build.js" }'

watch:
    @echo ... Starting server, running in background ...
    @echo ... Run: "make stop" to stop the server ...
    @tiny-lr &
    @rewatch index.js *.css -c "make build"

最后一件事就是在 html 页面里面嵌入 tiny-lr 的前端代码chrome

<!-- livereload snippet -->
 <script>document.write('<script src="http://'
  (location.host || 'localhost').split(':')[0]
  ':35729/livereload.js?snipver=1"><\/script>')
 </script>

若是只调 Chrome 的话能够使用 livereload 嵌入脚本代码。express

使用命令 make watch 启动服务,即可享受保存代码后项目自动构建而后浏览器自动刷新了。gulp

还有一个剩下的问题就是我不知道有没有什么好办法把改变的文件名传到那个 curl 的命令里面(除非单独写一条指令),若是tiny-lr知道改变的文件是css的话,它只会重加载那个css,这样调试起来更方便些。

相关文章
相关标签/搜索