Korean_hamster
지현의 개발자 성장과정
Korean_hamster
전체 방문자
오늘
어제
  • 분류 전체보기 (122)
    • Front-End Developer (79)
      • Project (12)
      • HTML (8)
      • CSS (17)
      • Computer Science (9)
      • JavaScript (20)
      • React (13)
    • 이런저런 생각 (7)
    • 주간 성장회고 (24)
    • English (0)
    • 리뷰 (2)
    • Books (5)

블로그 메뉴

  • 방명록

공지사항

인기 글

태그

  • 반응형웹
  • CS
  • 면접관님
  • 라우터
  • js
  • 멋쟁이사자처럼
  • 비전공개발자
  • fetch
  • AtomicHabits
  • 프론트앤드스쿨
  • 멋사
  • 프론트앤드
  • 깃헙
  • 리액트
  • 비전공자개발자
  • 깃
  • CSS
  • flex
  • HTML
  • sass

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Korean_hamster

지현의 개발자 성장과정

Front-End Developer/React

영혼없이 썼던 import React from 'react' - 안써도 된다는데?

2022. 6. 13. 14:08

궁금했다.

 

create-react-app 하면 항상 맨 위에 있길래.

 

그래서 찾아봤다.

 

리액트 공식문서

아~ 최상위 API구나. 그래서 항상 기본처럼 딸려있었구나.

(이렇게 react 모듈을 불러와서 실행해주는건 Node.js에서 지원해줌)

그래. 그 수많은 모듈 중 하나.

 

그럼 이녀석이 하는 일은 뭐냐? 

그건 공식문서를 보면 알 수 있다.

이 import React를 이해하려면 JSX Transform이라는걸 먼저 알아야 한다.

 

 

 

What’s a JSX Transform?

 

Browsers don’t understand JSX out of the box, so most React users rely on a compiler like Babel or TypeScript to transform JSX code into regular JavaScript. Many preconfigured toolkits like Create React App or Next.js also include a JSX transform under the hood.

 

-> 브라우저는 우리가 리액트를 쓸 때 흔히 사용하는 JSX문법을 이해할 수 없기때문에 Babel이나 TypeScript같은 컴파일러가 필요하다. JSX문법을 React.createElement(...) 형태로 바꿔주는 것이다.

 

 

 

이런 코드가 있다면, JSX Transform을 통해

import React from 'react';

function App() {
  return <h1>Hello World</h1>;
}

 

이렇게 변환되는 것이다.

import React from 'react';

function App() {
  return React.createElement('h1', null, 'Hello world');
}

 

지금 위 코드에서 항상 import React from 'react'가 있는 이유가 바로 이 방식에서는 React를 참조해야만 하기 때문에 그렇다.

아래와 같이 설명해주고있다.

 

 

 

이러한 방식이 완전하지 않은 것에는 아래와 같은 이유가 있다고 공식문서는 말한다.

 

However, this is not perfect:

  • Because JSX was compiled into React.createElement, React needed to be in scope if you used JSX.
  • There are some performance improvements and simplifications that React.createElement does not allow.

(대충 React를 꼭 네 프로젝트의 스코프 안에 넣어줘야하고(우리가 import하는 행위) 퍼포먼스나 기술제약이 있다는 소리)

 

 

 

 

그런데... 이제 더이상 import안해도 된다고?

 

그런데 이거봐라. 문서를 더 읽다보니 React 17버전부터는 없어도 된다고 하네?

 

To solve these issues, React 17 introduces two new entry points to the React package that are intended to only be used by compilers like Babel and TypeScript. Instead of transforming JSX to React.createElement, the new JSX transform automatically imports special functions from those new entry points in the React package and calls them.

 

(이러한 문제를 해결하기 위해 새로운 JSX변환에서는 자동으로 그러한 기능을 가진 함수를 import하고 실행한다고 한다.)

 

앞으로는 import가 없어도

function App() {
  return <h1>Hello World</h1>;
}

 

이렇게 알아서 JSX를 react/jsx-runtime의 jsx함수로 변환하는데, 개발자가 직접 react/jsx-runtime참조를 명시할 필요 없이, 빌드시점에 babel이 inject하는 방식으로 변경되었다. (아무것도 안해도 된다는 소리!)

// Inserted by a compiler (don't import it yourself!)
import {jsx as _jsx} from 'react/jsx-runtime';

function App() {
  return _jsx('h1', { children: 'Hello world' });
}

 

신기하다!! 실제로 컴포넌트 작업을 하던 파일에서 improt React부분을 제거해보았는데 문제없이 정상 작동하는 것을 확인할 수 있었다.

 

 

다만

 

(But we would still need to import React in order to use Hooks or other exports that React provides.)

 

훅이나 React가 제공하는 exports들을 사용하는 경우에는 여전히 import React가 필요하다고 말해준다.

 

 

 

결론

 

훅이나 다른 exports를 사용하지 않을때는 이제 import React 할 필요 없다.

나 이제 리액트 영혼 있다.

공식문서 열심히 보자.

저작자표시

'Front-End Developer > React' 카테고리의 다른 글

Router v6 헷갈려서 공부해봤다. 기초정리  (0) 2022.06.14
React를 한다면 무조건 알아야 할 - useRef 1편  (0) 2022.06.13
콘솔로그가 왜 두번씩 출력되는거야? - StrictMode  (0) 2022.06.13
리액트.... 이미지가 액박이 뜬다고?  (0) 2022.06.10
JS기초가 부족하면 React가 망한다는 말 진짜였네  (1) 2022.06.08
    Korean_hamster
    Korean_hamster
    Keep pushing myself to the limits

    티스토리툴바