
프론트엔드
Web Components웹 컴포넌트
웹 컴포넌트(Web Components)는 프레임워크 없이 재사용 가능한 UI 컴포넌트를 만들기 위한 W3C 표준 기술 모음이다. Custom Elements, Shadow DOM, HTML Templates 세 가지 기술로 구성된다.
Custom Elements
javascript
class MyButton extends HTMLElement {
static observedAttributes = ['label', 'disabled'];
connectedCallback() {
this.render();
}
attributeChangedCallback(name, oldVal, newVal) {
this.render();
}
render() {
this.innerHTML = `
<button ${this.hasAttribute('disabled') ? 'disabled' : ''}>
${this.getAttribute('label') || 'Click me'}
</button>
`;
}
}
customElements.define('my-button', MyButton);Shadow DOM
javascript
class MyCard extends HTMLElement {
constructor() {
super();
// Shadow DOM 생성 (외부 CSS와 격리)
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
:host { display: block; border: 1px solid #ccc; padding: 16px; }
.title { font-size: 1.2em; font-weight: bold; }
</style>
<div class="title"><slot name="title"></slot></div>
<slot></slot>
`;
}
}
customElements.define('my-card', MyCard);HTML Templates
html
<template id="product-card">
<style>
.card { border: 1px solid #ddd; padding: 1rem; }
</style>
<div class="card">
<img class="image" alt="">
<h3 class="name"></h3>
<p class="price"></p>
</div>
</template>
<script>
const template = document.getElementById('product-card');
const clone = template.content.cloneNode(true);
clone.querySelector('.name').textContent = 'Product A';
document.body.appendChild(clone);
</script>프레임워크와의 통합
tsx
// React에서 웹 컴포넌트 사용
function App() {
return <my-button label="Hello" />;
}
// 양방향 데이터 바인딩은 별도 처리 필요