Lit와 Web Component
Lit 란?
Lit
📣 Check out our brand-new Tutorials page and Lit YouTube Channel!Simple. Fast. Web Components.Skip the boilerplateBuilding on top of the Web Components standards, Lit adds just what you need to be happy and productive: reactivity, declarative templates
lit.dev
Lit는 가볍고 빠르게 웹 컴포넌트를 만들 수 있는 라이브러리이다.
Lit 공식 사이트 코드를 참고하여 웹 컴포넌트 사용법과 클래스에 대해 공부한 내용을 정리해 보았다.
웹 컴포넌트
: 충돌 걱정 없는 캡슐화 기능을 갖추고, 재사용 가능한 커스텀 엘리먼트를 생성하기 위한 다양한 기술들의 모음
아래 코드는 Lit 공식 사이트에 있는 Lit로 구현한 커스텀 엘리먼트 예시이다.
import {html, css, LitElement} from 'lit';
export class SimpleGreeting extends LitElement {
static styles = css`p { color: blue }`;
static properties = {
name: {type: String},
};
constructor() {
super();
this.name = 'Somebody';
}
render() {
return html`<p>Hello, ${this.name}!</p>`;
}
}
customElements.define('simple-greeting', SimpleGreeting);
이번 글에선 위 코드를 자세히 알아보려 한다.
커스텀 엘리먼트 API
웹 document의 커스텀 엘리먼트의 컨트롤러는 CustomElementRegistry 객체이다.
이 객체로 커스텀 엘리먼트를 등록할 수 있다.
customElements.define('simple-greeting', SimpleGretting);
CustomElementRegistry.define()의 메서드를 사용하여 커스텀 엘리먼트를 등록할 수 있다.
이 메서드의 인자로는 커스텀 엘리먼트 명, class 객체, (optional) 상속받는 내장 요소가 있다면 내장 요소 명시가 포함된다.
엘리먼트 명은 대시가 꼭 포함되어야 한다.
<simple-greeting name="World"></simple-greeting>
커스텀 엘리먼트를 정의했다면 HTML에서 위와 같이 호출할 수 있다.
Class
class PopupInfo extends HTMLElement {
constructor() {
super();
...
}
}
표준 웹 컴포넌트를 구성하는 구조를 살펴보면 HTMLElement 클래스를 상속받은 클래스를 정의한다.
Lit는 LitElement를 상속받은 클래스를 구현한다.
클래스 내부를 살펴보자...
constructor
: 클래스의 인스턴스 객체를 생성하고 초기화하는 메서드이다. 클래스 내에 한 개만 존재할 수 있다.
클래스를 상속받고 있으니 super()를 항상 호출을 해주어야 프로토타입 체인이 확립될 수 있다.
프로토타입 체인
: JavaScript는 프로토타입 기반 언어이다.
모든 객체들이 메소드와 속성들을 상속받기 위해 프로토타입 객체를 가진다는 의미이며, 프로토타입 객체는 상위 프로토타입 객체로부터 메소드와 속성을 상속 받을수 있고 그 상위 프로토타입 객체도 마찬가지로 더 상위 프로토타입 객체로부터 메소드와 속성을 상속받을 수 있다. 이를 프로토타입 체인이라 한다.
static
: 클래스의 정적 메서드를 정의한다.
프로토타입이 아닌 클래스 함수 자체에 메소드를 설정하는 것이다.
다시 말하자면 static 키워드는 어떤 특정한 객체가 아닌 클래스에 속한 함수를 구현하고자 할 때 사용된다.
static 예제 코드)
class StaticMethodCall{
static staticMethod() {
return 'static method has been called'
}
normalMethod() {
return 'normal method has been called'
}
}
StaticMethodCall.staticMethod()
// 'static method has been called'
StaticMethodCall.normalMethod()
// error. StaticMethodCall.normalMethod is not a function
const newStaticMethodCall = new StaticMethodCall()
newStaticMethodCall.staticMethod()
// newStaticMethodCall.staticMethod is not a function
newStaticMethodCall.normalMethod()
// 'normal method has been called'
위 코드는 MDN 문서에서 참고한 것이다.
static - JavaScript | MDN
static 키워드는 클래스의 정적 메서드를 정의합니다.
developer.mozilla.org
클래스가 new를 통해 클래스 객체로 인스턴스화 되면 static으로 설정한 메서드는 호출할 수 없는 것을 알 수 있다.
Lit에서는 style과 properties를 static으로 정의하였다.
static properties의 자세한 내용은 다음 링크를 참고해보면 좋을 것 같다.
Reactive properties – Lit
Reactive propertiesContentsLit components receive input and store their state as JavaScript class fields or properties. Reactive properties are properties that can trigger the reactive update cycle when changed, re-rendering the component, and optionally b
lit.dev
나도 아직 공부 중이기 때문에 다음에 자세히 정리해 봐야지
템플릿 리터럴
Lit에선 JavaScript의 템플릿 리터럴을 사용하여 html, css를 작성한다.
html`<p>Hello, ${this.name}!</p>`
css`p { color: blue }`;
템플릿 리터럴은 ``(백틱)을 사용하여 문자를 표기한다.
변수나 수식은 ${ } 내부에 선언할 수 있어서 ""나 ''로 표현한 문자열보다 간편하고 가독성이 좋다.
Lit에선 render() 함수를 사용하여 html 태그를 리턴해주었다.
지금까지 Lit에 대해 알아봤다기 보다는 JavaScript 클래스 위주로 알아보았다.
기본적인 내용에 대해 정리해 보면 좋을 것같아서 Lit 코드 구조를 보며 공부해 보았다.
앞으로 더 공부하면서 웹 표준, 모던 자바스크립트 위주로 정리해 나갈 예정이다.
