webpack 에서 Uncaught ReferenceError: React is not defined 오류가 나는 현상

milkbottle·2024년 7월 29일

React

목록 보기
29/33

Uncaught ReferenceError: React is not defined

npx 없이 리액트 프로젝트 만들기를 하고 npm run start를 했는데 아래와 같은 오류 덩어리가 생기는 현상이다.


실제 코드 레벨로 분석하면 React를 참조하지 못하는게 원인으로 예상할 수 있다.

해결법

babel 에 automatic 설정

// 수정 전
module.exports = {
  presets: [
    '@babel/preset-react',
    '@babel/preset-env',
    '@babel/preset-typescript',
  ],
};

// 수정 후
module.exports = {
  presets: [
    ['@babel/preset-react', { runtime: 'automatic' }],
    '@babel/preset-env',
    '@babel/preset-typescript',
  ],
};

automatic 옵션을 주어 babel의 react 변환방식을 변경한다.

webpack 에 automatic 설정

// 수정 전
{
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react'],
          },
        },
      },
      ...
    ], ...
   	...
  }...
      
// 수정 후
      {
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env',
              ['@babel/preset-react', { runtime: 'automatic' }],
            ],
          },
        },
      },
      ...
    ], ...
   	...
  }...

여기도 마찬가지로 automatic 옵션을 준다.

autmomatic 옵션이란?

react v17 부터 jsx 런타임 개념이 변경되어 classic -> autmomatic 으로 변경해줘야한다.
이전 글에도 같은 이유로, 다르게 설정해하는 부분이 있다.

참고

0개의 댓글