> For the complete documentation index, see [llms.txt](https://yamoo9.gitbook.io/webpack/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yamoo9.gitbook.io/webpack/react/create-your-own-react-app/configure-polyfills.md).

# 폴리필 구성

## 1. 폴리필, Unetch 설치

[core-js/stable](https://github.com/zloirock/core-js), [regenerator-runtime/runtime](https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js), [unfetch](https://www.npmjs.com/package/unfetch) 패키지를 프로젝트에 설치합니다.

{% tabs %}
{% tab title="패키지 설치" %}

```bash
npm i core-js regenerator-runtime unfetch
```

{% endtab %}
{% endtabs %}

{% hint style="danger" %}
Babel v7.4.0부터 [@babel/polyfill](https://babeljs.io/docs/en/babel-polyfill) 패키지는 사용되지 않습니다. 대신 ECMAScript 기능을 대체하는 [core-js/stable](https://github.com/zloirock/core-js),  제너레이터 함수 기능을 대체하는 [regenerator-runtime/runtime](https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js)을 사용합니다.
{% endhint %}

**polyfills** 디렉토리를 만든 후, `index.js`, `detect.js` 파일을 작성하고 저장합니다.

{% tabs %}
{% tab title="src/polyfills/index.js" %}

```javascript
import 'core-js/stable'
import 'regenerator-runtime/runtime'
import 'unfetch'
```

{% endtab %}

{% tab title="src/polyfills/detect.js" %}

```javascript
// 모던 브라우저 감지
const isModern = 'fetch' in window && 'assign' in Object

// 모던 브라우저가 아닌 경우
if (!isModern) {
  // 동적으로 <script> 요소 생성
  const scriptNode = document.createElement('script')
  // <script> 요소 속성 설정
  scriptNode.async = false
  scriptNode.src = './polyfills.js'
  // <head> 요소 안쪽 뒤에 삽입 (로딩)
  document.head.appendChild(scriptNode)
}
```

{% endtab %}
{% endtabs %}

개발용 `entry` 구성과 빌드용 `entry` 구성을 구분하기 위해 아래와 같이 조건 처리합니다.

{% tabs %}
{% tab title="webpack.config.js" %}

```javascript
module.exports = (_env, argv) => {
  // 엔트리(입력)
  const entry = {
    main: './src/index.js',
  }

  // 개발 모드
  if (isProd) {
    // 엔트리 추가
    entry = {
      ...entry,
      'polyfills': './src/polyfills/index.js',
      'detect.polyfills': './src/polyfills/detect.js',
    }
  }
  
  // 구성 객체 반환
  return {
    entry,
    // ...
  }
}
```

{% endtab %}
{% endtabs %}
