Front-end 로컬 서버 개발 환경 구성

손대중·2022년 4월 3일
0

개발 편의를 위해 로컬 서버를 띄워서 FE 를 실시간으로 테스트할 필요가 있다.

로컬 서버는 local-server.js 파일에 간단히 nodejs 로 코딩했다.

파일 요청시 타겟 파일을 리턴하도록 구현했으며, 추가로 SPA 이기 때문에 모든 url 은 index.html 을 리턴하도록 했다.

local-server.js

import http from 'http';
import path from 'path';
import fs from 'fs';
import url from 'url';

const __dirname = path.resolve();

const mimeType = {
  '.ico': 'image/x-icon',
  '.html': 'text/html',
  '.js': 'text/javascript',
  '.css': 'text/css',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.eot': 'aplication/vnd.ms-fontobject',
  '.ttf': 'aplication/font-sfnt',
}

const server = http.createServer((request, response) => {
  
  const urlPath = url.parse(request.url).pathname;
  const ext = path.parse(request.url).ext

  let resFilePath = path.join(__dirname, './public');
  let resMimeType = mimeType[ext];

  // 확장자가 없다 --> url 이라 간주하고, url 인 경우에는 index.html 리턴하도록 처리
  if (!resMimeType) {
    resFilePath += '/index.html';
    resMimeType = 'text/html';
  } else {
    resFilePath += urlPath;
  }

  fs.readFile(resFilePath, (err, data) => {
    if (err) {
      response.statusCode = 404;
      response.end('Not found');
    } else {
      response.statusCode = 200;
      response.setHeader('Content-Type', resMimeType);
      response.end(data);
    }
  });
});

server.listen(8080, () => { 
    console.log('Server is running...');
});

터미널에서 node local-server.js 명령어 실행시 정상적으로 동작하는 것 확인했다.

추가로 파일 수정시 바로바로 로컬 서버에 반영될 수 있도록 nodemon 모듈을 사용하기로 했다.

yarn global add nodemon 으로 설치하고, package.json 에 스크립트 명령어 추가한다.

"scripts": {
	"build": "node esbuild.js",
    "dev": "nodemon --watch src/ -e js,svelte --exec \"yarn build && node local-server.js\""
  },

추가한 스크립트의 의미는 src 디렉토리 내 js, svelte 파일에 변화가 있을때 빌드 수행 후 서버 재시작한다. 라는 의미이다.

이제 yarn dev 명령어 실행한 후에 js, svelte 파일 수정하면 바로 바로 브라우저에서 확인할 수 있다.
물론!!! 브라우저 새로 고침은 해야 한다 ㅋㅋㅋ

0개의 댓글