> 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/webpack/webpack-loaders/babel-loader.md).

# Babel 로더

## IE 웹 브라우저 대응 <a href="#support-ie-browsers" id="support-ie-browsers"></a>

Button 컴포넌트를 작성하면서 사용된 코드는 ES6의 class 문법입니다. (사실 이 실습 파일의 모든 코드는 ES6입니다.) 안타깝게도 [ES6+ 코드는 IE 웹 브라우저에서 제대로 지원하지 않습니다.](https://kangax.github.io/compat-table/es6/#ie11)

![](/files/-MTe6qRmygpuPg0g6-gF)

그러므로 class, ES Modules 등 ES6+ 문법을 사용한 앱 코드는 모두 IE에서 제대로 작동하지 않습니다. IE에서도 ES6 문법을 사용하려면 [Babel JavaScript 컴파일러](https://babeljs.io/)를 사용해야 합니다.

## Babel + Babel Loader 구성

[@babel/core](https://www.npmjs.com/package/@babel/core), [@babel/preset-env](https://www.npmjs.com/package/@babel/preset-env), [babel-loader](https://www.npmjs.com/package/babel-loader) 패키지를 프로젝트에 설치한 후, Webpack 구성 파일의 모듈 규칙 안에 로더를 설정합니다.

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

```bash
npm i @babel/core @babel/preset-env babel-loader -D
```

{% endtab %}

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

```javascript
module.exports = {
  module: {
    rules: [
      // Babel 파일 로더 설정
      {
        test: /\.m?js$/i,
        exclude: /node_modules/,
        use: {
          loader:'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
"exclude" 설정은 정규식과 매칭되는 디렉토리 또는 파일은 로더에 의한 번들링에서 제외됩니다.
{% endhint %}

{% hint style="info" %}
@babel/preset-env 프리셋은 Babel Foundation이 제공하는 번들로 유용한 Babel 플러그인 모음입니다. 이 프리셋을 설정하지 않으면 ES6+ 코드를 ES5로 컴파일 하지 않게 됩니다. (ES6+ 코드는 IE 미지원)
{% endhint %}

## 모듈 번들링 <a href="#module-bundle" id="module-bundle"></a>

`bundle` NPM 명령을 실행해 모듈을 번들링 합니다.

```bash
npm run bundle
```

번들링에 성공하면 브라우저 개발 도구 Sources 탭에서 ES5 코드로 컴파일된 Button 컴포넌트 코드를 볼 수 있습니다.

![](/files/-MTe8bJVPMtATICv5cp-)

## Babel 플러그인 <a href="#babel-plugins" id="babel-plugins"></a>

[@babel/plugin-proposal-class-properties](https://www.npmjs.com/package/@babel/plugin-proposal-class-properties) 플러그인은 속성 초기화(Initializer) 구문으로 선언 된 속성 뿐만 아니라, 정적(Static) 클래스 속성 또한 변환(Transform) 합니다.

{% hint style="info" %}
플러그인 이름 그대로 ES 표준에 제안된(proposal) class 속성을 변환 처리하는 플러그인입니다.
{% endhint %}

먼저 Button 컴포넌트 class 내부에 속성 초기화 또는 정적 클래스 속성 구문을 작성해봅시다.

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

```javascript
class Button {
  constructor(props) {
    this.props = { ...props }
  }
  
  // ES 표준에 제안된 정적 클래스 속성 구문
  static defaultProps = {
    type: 'button',
  }

  render(domNode = document.body) {
    // 속성 병합(mixins)
    const buttonNode = createElement('button', {
      ...this.defaultProps,
      ...this.props,
    })
    render(buttonNode, domNode)
  }
}

export default Button

```

{% endtab %}
{% endtabs %}

작성된 파일을 저장하고 번들링 하면 다음과 같은 오류가 발생합니다. 오류 내용은 실험적인 문법인 **classProperties**를 현재 사용할 수 없다는 문구입니다.

{% hint style="danger" %}
**ERROR** in **./src/components/Button/index.js** Module build failed (from ./node\_modules/babel-loader/lib/index.js): **SyntaxError**: /Users/yamoo9/Documents/PROJECT/js-senior-in-ogada/meetup(offline)/week01/02-setting-webpack/src/components/Button/index.js: **Support for the experimental syntax 'classProperties' isn't currently enabled** (13:16):

```javascript
  11 |   }
  12 |
> 13 |   defaultProps = {
     |                ^
  14 |     type: 'button',
  15 |   }
  16 |
```

{% endhint %}

오류를 해결하려면 @babel/plugin-proposal-class-properties를 사용할 수 있도록 설치하고 구성해야 합니다.

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

```bash
npm i @babel/plugin-proposal-class-properties -D
```

{% endtab %}

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

```javascript
module.exports = {
  module: {
    rules: [
      {
        test: /\.m?js/i,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          presets: ['@babel/preset-env'],
          // Babel 플러그인 설정
          plugins: ['@babel/plugin-proposal-class-properties']
        }
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

플러그인 사용을 위한 구성이 완료되면 오류 없이 번들링이 성공적으로 수행됩니다.

```bash
webpack 5.22.0 compiled successfully in 921 ms
```

{% hint style="info" %}
실습에서 설치해 사용한 플러그인 말고도 다양한 플러그인을 Babel JavaScript 컴파일러는 지원합니다. [Babel이 지원하는 플러그인 목록](https://babeljs.io/docs/en/plugins)을 참고해 사용하고자 하는 플러그인을 설치해 활용해보세요.
{% endhint %}

## 참고 <a href="#reference" id="reference"></a>

{% embed url="<https://webpack.js.org/loaders/babel-loader/>" %}

{% embed url="<https://babeljs.io/docs/en/babel-plugin-proposal-class-properties>" %}

## &#x20;<a href="#styling-button-component" id="styling-button-component"></a>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://yamoo9.gitbook.io/webpack/webpack/webpack-loaders/babel-loader.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
