'React' must be in scope when using JSX

milkbottle·2024년 7월 29일
0

React

목록 보기
28/33

오류


React 개발중 컴포넌트마다 빨간줄이 적힌 경우가 있다.

[{
	"resource": "/Users/milkbottle/Project/web/serverloan-client/src/ui/components/Header/Header.tsx",
	"owner": "eslint",
	"code": {
		"value": "react/react-in-jsx-scope",
		"target": {
			"$mid": 1,
			"path": "/jsx-eslint/eslint-plugin-react/tree/master/docs/rules/react-in-jsx-scope.md",
			"scheme": "https",
			"authority": "github.com"
		}
	},
	"severity": 8,
	"message": "'React' must be in scope when using JSX",
	"source": "eslint",
	"startLineNumber": 5,
	"startColumn": 5,
	"endLineNumber": 5,
	"endColumn": 21
}]

해결법

JSX를 사용하려면 React 스코프 내에서 사용되어야 한다.

즉, React 를 당겨오면 된다.
import React from 'react';를 추가한다.

단점

하지만 이 방법을 쓴다면, 매 컴포넌트마다 상단에 import React from 'react';를 추가해야해서 귀찮다.

또 다른 해결법

eslint를 사용한다면, 해당 rule를 추가한다.

그런데 내 프로젝트에서는 이방법을 사용하면

'React' must be in scope when using JSX라는 오류가

'React'은(는) UMD 전역을 참조하지만 현재 파일은 모듈입니다. 대신 가져오기를 추가해 보세요. 오류로 바뀌어 버린다.

그 이유는 바로 tsconfig.json을 설정을 제대로 하지 않은 것이다.

tsconfig.json파일에서 compilerOptionsjsx 값을 react-jsx로 준다.

{
  "compilerOptions": {
    "target": "es5" /* 프로젝트의 타겟 JavaScript 버전 */,
    "lib": ["dom", "dom.iterable", "esnext"] /* 사용 가능한 라이브러리 목록 */,
    "allowJs": true /* JavaScript 파일을 컴파일할 때 허용 여부 */,
    "skipLibCheck": true /* .d.ts 파일의 검사를 건너뛰는 여부 */,
    "esModuleInterop": true /* CommonJS 모듈과 함께 ES 모듈 인터프레이스를 사용할 수 있게 함 */,
    "allowSyntheticDefaultImports": true /* import x from 'foo' 형식의 구문에서도 default가 없는 모듈을 기본 모듈로 인식 */,
    "strict": true /* 엄격한 타입 검사 옵션 활성화 */,
    "forceConsistentCasingInFileNames": true /* 파일명의 일관된 캐싱 강제 */,
    "noFallthroughCasesInSwitch": true /* switch 문에서의 case 절에서의 case 절 누락 확인 */,
    "module": "esnext" /* ECMAScript 모듈 시스템 지정 */,
    "moduleResolution": "node" /* 모듈 해결 전략 지정 */,
    "resolveJsonModule": true /* .json 파일을 import할 수 있게 함 */,
    "isolatedModules": true /* 각 파일을 독립된 모듈로 처리 */,
    "jsx": "react-jsx" /* JSX 구문 사용 설정 */,
    "noEmit": true /* 출력 파일 생성하지 않음 */
  },
  "include": ["src"] /* 컴파일할 파일이 위치한 디렉토리 */
}

이런 식으로 말이다.

기존에는 "jsx": "react"였는데, "jsx": "react-jsx"로 하니까 수정이되었다.

"jsx": "react" vs "jsx": "react-jsx"

react v16 이하에서는 전자, v17 이상에서는 후자를 사용한다.

const element = <div>Hello</div>;

이러한 컴포넌트가 있다고 하면,
전자는 다음과 같이 변환된다.

const element = React.createElement("div", null, "Hello");

후자는 다음과 같이 변환된다.

const element = /*#__PURE__*/_jsx("div", {
  children: "Hello"
});

0개의 댓글