블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

'tiny-lr'에 해당되는 글 1

  1. 2017.04.04 [Gulp] Live reload 환경 만들기
2017. 4. 4. 10:59 Dev Environment/Build System

Gulp 빌드 환경에 파일이 변경되었을 때 자동으로 브라우져 화면을 업데이트해주는 Live reload환경을 접목해 본다.





Gulp 환경 만들기


gulp CLI를 설치한다.

$ npm i -g gulp-cli


npm 대신 속도가 빠르다는 yarn을 사용해 본다. yarn을 설치한다.

$ npm i -g yarn



테스트 폴를 생성하고,yarn을 이용해 package.json을 만든다. -y 플래그를 주면 모두 Yes로 응답해서 package.json을 생성해준다.

$ mkdir livereload && cd livereload

$ yarn init -y

yarn init v0.21.3

warning The yes flag has been set. This will automatically answer yes to all questions which may have security implications.

success Saved package.json

✨  Done in 0.06s.



index.html파일을 생성하고, gulp 패키지를 로컬에 설치한다. index.html에 간단한 body 태그를 넣는다. 

$ touch index.html

$ yarn add --dev gulp


TypeScript기반으로 파일을 작성하기 위해 다음 설정을 한다. [Typescript] NodeJS에서 Typescript 사용하기

$ yarn add --dev @types/node



gulp환경파일을 생성하고, default 태스크를 작성한다. gulp 명령을 실행하면 default 태스크가 실행된다.

$ touch Gulpfile.ts


// Gulpfile.js

const gulp = require('gulp');


gulp.task('default', function () {

  console.log('Gulp and running!')

});


// test

$ gulp

[09:27:23] Using gulpfile ~/prototyping/livereload/gulpfile.ts

[09:27:23] Starting 'default'...

Gulp and running!

[09:27:23] Finished 'default' after 71 μs





테스트 서버 환경 만들기


Express를 설치하고 정적 파일을 처리하는 서버를 생성한다.

$ yarn add --dev express


// Gulpfile.ts

const gulp = require('gulp');


function startExpress() {

  const express = require('express');

  const app = express();

  app.use(express.static(__dirname));

  app.listen(4000);

}


gulp.task('default', () => startExpress());


index.html 을 작성하고, gulp 명령을 수행한 다음 http://localhost:4000 호출해서 hi peter가 출력하면 정상작동이다. 

<!DOCTYPE html>

<html>

  <head>

    <meta charset="utf-8">

    <title></title>

  </head>

  <body>

    hi peter

  </body>

</html>


다음으로 livereload server 인 tiny-lr을 설치한다.

$ yarn add --dev tiny-lr


tiny-lr서버도 gulp환경에 넣는다. gulp명령을 실행하고 http://localhost:35729/ 접속해서 {"tinylr":"Welcome","version":"1.0.3"} 출력되면 정상작동이다. tiny-lr의 기본 포트는 35729 이다.

const gulp = require('gulp');


function startExpress() {

  const express = require('express');

  const app = express();

  app.use(express.static(__dirname));

  app.listen(4000);

}


function startLivereload() {

  const lr = require('tiny-lr')();

  lr.listen(35729);

}


gulp.task('default', () => {

  startExpress();

  startLivereload();

});





Livereload 환경 만들기


전체 동작방식은 다음과 같다.

  - 브라우져가 열리면 livereload.js는 tiny-lr과 웹소켓 연결을 맺는다.

  - 1) gulp.watch가 파일 변경을 감지한다. 

  - 1) gulp.watch는 변경파일에 대해 tiny-lr에게 reload 하라고 호출한다. 

  - 2) tiny-lr 서버는 livereload.js 모듈과 웹소켓으로 통신한다.

  - 3) livereload.js는 파일을 다시 요청한다. 

  - 화면이 refresh되면서 livereload.js와 tiny-lr 간 웹소켓 연결을 다시 맺는다. 





Express로 서비스하는 페이지가 livereload 처리하는 자바스크립트 로직을 넣기위해 connect-livereload NodeJS 미들웨어도 설치한다.

$ yarn add --dev connect-livereload


connect-livereload를 Express 미들웨어로 설정한다.

// Gulpfile.ts

function startExpress() {

  const express = require('express');

  const app = express();

  app.use(require('connect-livereload')());

  app.use(express.static(__dirname));

  app.listen(4000);

}



gulp.watch를 통해 변경된 파일의 목록을 tiny-lr에 전달하는 코드를 작성한다. 

const gulp = require('gulp');


function startExpress() {

  const express = require('express');

  const app = express();

  app.use(require('connect-livereload')());

  app.use(express.static(__dirname));

  app.listen(4000);

}


let lr;

function startLivereload() {

  lr = require('tiny-lr')();

  lr.listen(35729);

}


function notifyLivereload(event) {

  // `gulp.watch()` events 는 절대경로를 주기 때문에 상대 경로(relative)를 만든다.

  var fileName = require('path').relative(__dirname, event.path);


  lr.changed({

    body: {

      files: [fileName]

    }

  });

}


gulp.task('default', () => {

  startExpress();

  startLivereload();

  gulp.watch('*.html', notifyLivereload);

});


다시 gulp를 수행하고 브라우져에서 http://localhost:4000/index.html 을 호출한 후에 index.html의 내용을 변경하면 브라우져가 자동으로 refresh되는 것을 볼 수 있다. 브라우져에서 element검사를 하면 아래와 같이 livereload.js파일이 </body> 전에 자동 추가된다. (소스 참조)



위의 코드를 단순히 하기위해 gulp-livereload를 사용할 수도 있다. 샘플 파일: https://github.com/BISTel-MIPlatform/livereload-tiny-lr





참조

  - https://github.com/mklabs/tiny-lr

 - https://github.com/livereload/livereload-js

  - https://github.com/intesso/connect-livereload

  - https://github.com/vohof/gulp-livereload

posted by 윤영식
prev 1 next