웹팩과 함께 import React from "react" 안써보기

2023. 1. 6. 12:57React

'React' refers to a UMD global, but the current file is a module


그냥 기본설정대로 CRA를 썼을 때는 매번 JSX나 TSX의 최상단에

 

import React from "react";

 

이 코드를 넣어서 동작시켜야한다.

반면 Next.js와 같은 환경에서 동작시켰을 때는 저 코드 없이도 JSX를 사용할 수 있는데 그 설정 역시 공식문서에서 다뤄져 있었다.

 

https://ko.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html

 

Introducing the New JSX Transform – React Blog

Although React 17 doesn’t contain new features, it will provide support for a new version of the JSX transform. In this post, we will describe what it is and how to try it. What’s a JSX Transform? Browsers don’t understand JSX out of the box, so most

ko.reactjs.org

 

webpack.config.ts


webpack을 통해 공통적으로 import되는 라이브러리를 설정해줄 수 있는데 해당 코드의 plugins부분에 넣어주면 된다.

// webpack.config.ts

const config = {
  //..
  resolve: {},
  entry: {},
  module: {},
  plugins: [
    //..
    new webpack.ProvidePlugin({
      React: 'react';
    })
  ],
  //..
}

 

다만 이 코드는 웹팩으로 빌드될 때 넣어지는 코드고, 에디터 상에서 문법 체크를 해주는 tsconfig.json에서 한 번 더 설정을 해줘야 에러가 나지 않는다.

 

// tsconfig.json
{
  "compilerOptions": {
    //..
    "jsx": "react-jsx",
    //..
  }
}

 

 

에디터에서도 빌드에서도 에러가 나지 않도록 import React from "react"를 자동화 시켜봤다.