# CSS 로더

## Style Loader + CSS Loader 구성

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

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

```bash
npm i style-loader css-loader -D
```

{% endtab %}

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

```javascript
module.exports = {
  module: {
    rules: [
      // CSS 파일 로더 설정
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

## Button 컴포넌트

간단한 Button 컴포넌트를 만들어 스타일링 하는 실습을 진행해봅니다. 컴포넌트 클래스, CSS 스타일 파일을 작성합니다.

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

```javascript
import { createElement, render } from '../../modules/DOM'
import './style.css'

/* -------------------------------------------------------------------------- */

class Button {
  constructor(props) {
    this.props = { ...props }
  }

  render(domNode = document.body) {
    const buttonNode = createElement('button', this.props)
    render(buttonNode, domNode)
  }
}

export default Button
```

{% endtab %}

{% tab title="src/components/Button/style.css" %}

```css
.button {
  cursor: pointer;
  border: 0;
  border-radius: 4px;
  padding: 0.6em 0.94em;
  background: #111;
  color: #fff;
}
```

{% endtab %}
{% endtabs %}

엔트리 파일(`src/index.js`)에서 Button 컴포넌트 모듈을 불러온 후, Button 생성/렌더링 하도록 작성합니다.

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

```javascript
import { success } from './modules/LOGGER.js'
import Button from './components/Button'


// Button 컴포넌트 인스턴스 생성
const button = new Button({
  className: 'button',
  onClick(e) {
    success('Button 컴포넌트의 인스턴스를 클릭했습니다.')
  },
  children: 'Button 컴포넌트',
})

// Button 렌더링
button.render(rootNode)
```

{% endtab %}
{% endtabs %}

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

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

```bash
npm run bundle
```

오류 없이 번들링이 완료되어도 배포 디렉토리(`dist`) 안에는 CSS 파일이 보이지 않습니다. 이유가 뭘까요?

{% tabs %}
{% tab title="번들링 결과" %}

```bash
dist/
├── 861b3c3b709916519ce293d61ec0b0aa.png
└── main.js
```

{% endtab %}
{% endtabs %}

웹 브라우저 개발 도구 Elements 패널을 확인해보면 이유를 알 수 있습니다. CSS 파일 로더는 기본적으로 HTML 문서의 \<head> 영역에 인터널(internal) 스타일 방식으로 스타일 코드를 추가합니다.

![](https://1127883942-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MTbexhuB2p5ev8QaGgg%2F-MTdoMpdqV359W-JLL_V%2F-MTdoaWLSL_UZ_i5KkvW%2Fimage.png?alt=media\&token=ea401497-a8e7-491b-9b38-6eefbf31a79a)

{% hint style="info" %}
HTML 문서에 포함시키지 않고 별도의 CSS 파일로 내보내길 원한다면 [CSS 파일 추출](https://yamoo9.gitbook.io/webpack/webpack/webpack-plugins/extract-css-files)을 참고하세요.
{% endhint %}

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

{% embed url="<https://webpack.js.org/guides/asset-management/#loading-css>" %}
