Skip to content

Instantly share code, notes, and snippets.

@velopert
Created January 20, 2018 04:25
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save velopert/21896de87566628b38b7ecb95973a7b3 to your computer and use it in GitHub Desktop.
Save velopert/21896de87566628b38b7ecb95973a7b3 to your computer and use it in GitHub Desktop.
react-hot-loader.md

react-hot-loader 적용하기

react-hot-loader 는 코드가 변경되었을 때 페이지를 새로고침하지 않고 바뀐부분만 빠르게 교체해주는 라이브러리입니다. 비록, 리액트 어플리케이션을 개발 할 때 필수적인 개발도구는 아니지만, 앱의 규모가 커지면 개발서버가 수정될때마다 새로고침이 된다면 딜레이가 발생되어 개발의 흐름이 중간중간 1~6초씩 끊길 수도 있습니다. 특히, styled-components 를 사용하게 되는 경우엔, 스타일이 JS 안에 있어서, 스타일을 수정 할 때마다 새로고침이 된다는게 조금 불편할수도 있겠죠.

이렇게 자바스크립트 코드의 일부분만 교체하는 기능은 웹팩 개발서버의 기능이기 때문에, 라이브러리 없이도 코드를 조금 건들여주면 가능합니다. 하지만, 어플리케이션의 state 를 계속 유지하려면 과정이 복잡하기 때문에 라이브러리의 힘을 빌릴 필요가 있습니다.

이전에는, webpack 쪽에서 설정을 해야 될 것이 있었기 때문에, 무조건 yarn eject 를 해주어야 했지만, 이제는 바벨 설정만 하면 되므로 eject 하는 작업은 선택적입니다. 최신 react-hot-loader 는 굉장히 많이 편해졌답니다.

설치하기

react-hot-loader 를 설치하세요.

$ yarn add --dev react-hot-loader@next

뒤에 @next 를 붙여주시면, 최신버전을 받아오게 됩니다.

설치가 완료된 다음에는, package.json 에서 babel 설정을 하세요.

package.json

{
  "name": "hot-loader-next",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-hot-loader": "next",
    "react-scripts": "1.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
      "react-hot-loader/babel"
    ]
  }
}

원래 기본적으로는 "presets": ["react-app"] 만 있는데요, 설정에 플러그인 부분을 추가해주었습니다.

hot 설정하기

그 다음엔, 프로젝트의 최상위 컴포넌트(지금의 경우엔 App 이 되겠죠?) 에서 hot 을 불러온 뒤 내보낼 때 hot(module)(App) 형식을 작성해주시면 됩니다.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { hot } from 'react-hot-loader'

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload!
        </p>
      </div>
    );
  }
}

export default hot(module)(App);

정리

벌써 끝났습니다! react-hot-loader v4 가 되면서 작업이 굉장히 간단해졌습니다. 이전에는 설정해야 할 것이 꽤 있었거든요. 저의 경우에는 실무에서 react-hot-loader 를 잘 사용하지 않습니다. 개발을 하게 될 때 없어도 별로 큰 지장이 되지 않거든요 (어짜피 페이지는 파일 저장하면 새로고침이 트리거되기 때문입니다). 만약에 프로젝트에서 사용을 하게 된다면, 코드를 저장 할 때마다 페이지를 새로고침하는것이 거슬리기 시작 할 때 쯤 도입을 하는것을 추천드립니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment