[TIL] React 입문: 환경설정부터 배포까지

minami·2021년 5월 14일
0

React

목록 보기
1/12
post-thumbnail

React

Facebook에서 만든 JS UI 라이브러리

1. 소개

  • React의 특징
    • 사용자 정의 태그를 사용가능하게 해준다 ➡ Component
    • Component의 특징
      1. 코드의 가독성을 높여준다.
      2. 재사용성이 높다.
      3. 유지보수가 편리하다.

2. 개발환경 세팅

React 공식문서

2-1. 온라인 코드 편집기 사용

2-2. NPM을 사용해서 Create React App 설치

  • NPM: Node.js를 사용한 앱 설치를 도와주는 프로그램
  • 설치 순서
    1. Node.js 설치

    2. Node.js 설치 확인

      > node -v
      v14.17.0
      
      > npm -v
      6.14.13
    3. Create React App 설치

      > npm install -g create-react-app

      3-1. React 공식문서의 Create React App 설치 및 실행 방법

      > npx create-react-app my-app
      > cd my-app
      > npm start
      • npxnpm처럼 별도로 로컬 컴퓨터에 설치하지 않고 임시로 리액트 앱을 설치하여 사용 후 삭제되도록 하는 명령어
        • 장점
          • 항상 최신 버전 사용 가능
          • 간편하게 리액트 앱 사용 가능
    4. Create React App 설치 확인

      > create-react-app -V
      4.0.3

2-3. Create React App을 이용한 개발환경 구축

  1. 디렉토리로 지정해줄 새 폴더 생성

  2. 생성한 폴더로 이동

    > cd react-app
  3. create-react-app 명령어 실행

    > create-react-app .

3. React 샘플 웹앱 실행

  1. React 앱 실행
    PS > npm run start
    • 정상적으로 실행되었을 때 - Terminal
    • 정상적으로 실행되었을 때 - 웹 브라우저
  2. React 앱 종료

    종료 키 ctrl + c

4. React 앱 기본 구조 분석

4-1. index.html과 index.js

  • index.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    import reportWebVitals from './reportWebVitals';
    
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById('root')
    );
    
    // If you want to start measuring performance in your app, pass a function
    // to log results (for example: reportWebVitals(console.log))
    // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
    reportWebVitals();
    
    • 'root': index.html<div>태그 이름이다.

      <body>
          <noscript>You need to enable JavaScript to run this app.</noscript>
          <div id="root"></div>
          <!--
            This HTML file is a template.
            If you open it directly in the browser, you will see an empty page.
      
            You can add webfonts, meta tags, or analytics to this file.
            The build step will place the bundled scripts into the <body> tag.
      
            To begin the development, run `npm start` or `yarn start`.
            To create a production bundle, use `npm run build` or `yarn build`.
          -->
       </body>
    • <App />: src 폴더 아래의 App.js를 말한다.

      • App.js를 함수에서 class로 변경하기

        //function으로 선언되어 있을 때
        import logo from './logo.svg';
        import './App.css';
        
        function App() {
          return (
            <div className="App">
              <header className="App-header">
                <img src={logo} className="App-logo" alt="logo" />
                <p>
                  Edit <code>src/App.js</code> and save to reload.
                </p>
                <a
                  className="App-link"
                  href="https://reactjs.org"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  Learn React
                </a>
              </header>
            </div>
          );
        }
        
        export default App;
        
        //class로 변경했을 때
        import logo from './logo.svg';
        import './App.css';
        import { Component } from 'react';
        
        class App extends Component {
          render() {
            return (
              <div className="App">
                <header className="App-header">
                  <img src={logo} className="App-logo" alt="logo" />
                  <p>
                    Edit <code>src/App.js</code> and save to reload.
                  </p>
                  <a
                    className="App-link"
                    href="https://reactjs.org"
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    Learn React
                  </a>
                </header>
              </div>
            );
          }
        }
        
        export default App;
      • class로 변경 시 에러

        TypeError: Class constructor App cannot be invoked without 'new'
        
        //해결방법: Component import가 잘 안 되어 있어서 발생한 에러로 import를 제대로 해 주면 된다.
        import { Component } from 'react';

4-2. index.css

  • index.css 수정하기

    body {
      background-color: mistyrose;
    }

5. 배포

5-1. React 웹앱 배포하는 방법

  1. build하기
    > npm run build
    • 모듈을 찾지 못하는 에러

      Failed to compile.
      
      Cannot find module 'vendors'
      Require stack:
      - C:\react-app\node_modules\postcss-merge-rules\dist\index.js
      - C:\react-app\node_modules\cssnano-preset-default\dist\index.js
      - C:\react-app\node_modules\cssnano\dist\index.js
      - C:\react-app\node_modules\optimize-css-assets-webpack-plugin\src\index.js
      - C:\react-app\node_modules\react-scripts\config\webpack.config.js
      - C:\react-app\node_modules\react-scripts\scripts\build.js
      
      
      npm ERR! code ELIFECYCLE
      npm ERR! errno 1
      npm ERR! react-app@0.1.0 build: `react-scripts build`
      npm ERR! Failed at the react-app@0.1.0 build script.
      npm ERR! This is probably not a problem with npm. There is likely additional logging outonal logging output above.
                                                                                              put above.
      npm ERR! A complete log of this run can be found in:
      npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2021-05-14T06_42_45_970Z-debu_42_45_970Z-debug.log
      
      #해당 모듈을 설치해주고 다시 빌드한다
      C:\react-app> npm i react vendors
  2. build디렉토리 자동생성
  3. 웹 서버 실행
    PS C:\react-app> npx serve -s build
    • 결과

5-2. React 웹앱 build버전을 배포했을 때의 장점

  • 용량이 줄어든다
    • 개발할 때의 용량
    • build버전을 배포했을 때의 용량

🐍뱀발

본격적인 인턴 생활의 첫 과제로 React 공부를 시작하면서 말로만 듣던 생활코딩 강의를 듣게 되었다. 한 강의가 10분도 안 되게 짧으면서도 간결하고 정확한 설명 덕분인지 그동안 배우고 싶었던 리액트 첫 시작도 산뜻해 우와😍

그래서인지 오늘 하루만에 React 기본 강의 전체 40강 중에 절반 가까운 18강을 들었는데 재밌었다. 얼른 배워서 회사에서 개발중인 프로그램 소스코드 분석도 빨리 끝내고 조금이라도 기여하고 싶은 마음이 크다. 다음주까지는 강의 모두 들을 수 있을 것 같은데 시간 나면 React 활용해서 쟈근 토이 프로젝트라도 해봐야 할 것 같다. NodeJS도 React 덕에 처음 써보고, 이래저래 처음 해보는 것들이 아직도 많지만 그래서 더 재밌고 설렌다.

profile
함께 나아가는 개발자💪

0개의 댓글