관리 메뉴

Silver Library (Archived)

Web Component 는 도대체 어떻게 사용할까? 본문

Personal DB/Mainly for Front-end

Web Component 는 도대체 어떻게 사용할까?

Chesed Kim 2021. 10. 21. 23:18
반응형

개요.

이 글은 custom web component 의 사용법에 대해 알아보고자 한다.

 

이 글에서 내린 정의:

웹 컴포넌트(web component) 가 바로 그 전신이자 근원이다.

 

웹 컴포넌트 | MDN

웹 컴포넌트는 그 기능을 나머지 코드로부터 캡슐화하여 재사용 가능한 커스텀 엘리먼트를 생성하고 웹 앱에서 활용할 수 있도록 해주는 다양한 기술들의 모음입니다.

developer.mozilla.org

 

웹 컴포넌트는 / 그 기능을 나머지 코드로부터 캡슐화하여 / 재사용 가능한 / 커스텀 엘리먼트를 생성하고 / 웹 앱에서 / 활용할 수 있도록 해주는 / 다양한 기술들의 모음입니다.

 

그리고, web API 도 개요만큼은 알아두었으면 한다.

 

Introduction to web APIs - Learn web development | MDN

At this point, you should have a good idea of what APIs are, how they work, and what you can do with them in your JavaScript code. You are probably excited to start actually doing some fun things with specific APIs, so let's go! Next up, we'll look at mani

developer.mozilla.org

끝으로 component 와 props 에 대한 개요글.

왜 이걸 알아두는게 좋다 판단했나라고 묻는다면, 'component 라는 건, 어째 props 와 유사점이 있다는 느낌이다.'

라는 의문이 들었기 때문이다.

 

Components와 Props – React

A JavaScript library for building user interfaces

ko.reactjs.org

언제 쓰이는가?

현재 까지는 react.js, JS 에서 사용 되는 것이 확인 가능하다.

 

어떻게/어떤 상황에서 쓰이는가?

이 해답을 알기 까지 하루 종일이 걸렸다. 우선 정의부터 읽어봐야한다.

 

"Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps."

 

Web Components are a set of features that provide a standard component model for the Web[1] allowing for encapsulation and interoperability of individual HTML elements.

Primary technologies used to create them include:[2]

  • Custom Elements: APIs to define new HTML elements
  • Shadow DOM: encapsulated DOM and styling, with composition
  • HTML Templates: HTML fragments that are not rendered, but stored until instantiated via JavaScript[3]

 

드디어 용도를 제한할 수 있게 되었다. 집중할 범위가 줄고, 에너지 낭비가 줄었다.

참고로 한글은 다음과 같다.

 

커스텀 엘리먼트: 커스텀 엘리먼트와 그 동작을 정의할 수 있도록 해주는 JavaScript API 의 집합으로, 사용자 인터페이스에서 원했던대로 사용될 수 있습니다.

  • Custom elements: 사용자 인터페이스에서 원하는대로 사용할 수있는 사용자 정의 요소 및 해당 동작을 정의 할 수있는 JavaScript API 세트입니다.
  • Shadow DOM: 캡슐화된 "그림자" DOM 트리를 엘리먼트 — 메인 다큐먼트 DOM 으로부터 독립적으로 렌더링 되는 — 를 추가하고 연관된 기능을 제어하기 위한 JavaScript API 의 집합. 이 방법으로 엘리먼트의 기능을 프라이빗하게 유지할 수 있어, 다큐먼트의 다른 부분과의 충돌에 대한 걱정 없이 스크립트와 스타일을 작성할 수 있습니다.
  • HTML 템플릿: <template>  <slot> 엘리먼트는 렌더링된 페이지에 나타나지 않는 마크업 템플릿을 작성할 수 있게 해줍니다. 그 후, 커스텀 엘리먼트의 구조를 기반으로 여러번 재사용할 수 있습니다.

그리고 중요한 점이 여기에 있다.

웹 컴포넌트를 구현하기 위한 기본 접근법은 일반적으로 다음과 같습니다.

  1. ECMAScript 2015 클래스 문법(자세한 내용은 Classes에서 확인)을 사용해 웹 컴포넌트 기능을 명시하는 클래스를 생성합니다.
  2. CustomElementRegistry.define() (en-US) 메소드를 사용해 새로운 커스텀 엘리먼트를 등록하고, 정의할 엘리먼트 이름, 기능을 명시하고 있는 클래스, (선택적으로) 상속받은 엘리먼트를 전달합니다.
  3. 필요한 경우, Element.attachShadow() (en-US) 메소드를 사용해 shadow DOM 을 커스텀 엘리먼트에 추가합니다. 일반적인 DOM 메소드를 사용해 자식 엘리먼트, 이벤트 리스너 등을 shadow DOM 에 추가합니다.
  4. 필요한 경우, <template>  <slot> 을 사용해 HTML 템플릿을 정의합니다. 다시 일반적인 DOM 메소드를 사용해 템플릿을 클론하고 shadow DOM 에 추가합니다.
  5. 일반적인 HTML 엘리먼트처럼, 페이지의 원하는 어느곳이든 커스텀 엘리먼트를 사용할 수 있습니다.

그래서...그래서 사용방법은?

진지하게, 이 링크를 통해서 이해하는게 더 이득이라는 판단이 들어서 요약 대신 링크를 남겨두겠다.

 

Using custom elements - Web Components | MDN

One of the key features of the Web Components standard is the ability to create custom elements that encapsulate your functionality on an HTML page, rather than having to make do with a long, nested batch of elements that together provide a custom page fea

developer.mozilla.org

nodes(node.js 가 아니다)가 대체 뭘 의미 하지? 라고 한다면 여기를.

 

HTMLElement - Web APIs | MDN

The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.

developer.mozilla.org

편의상 정의한다면 component 는 정확하게 좌표를 찍어둔 기능 캡슐덩어리.

 

그나저나 props 는 정확히 뭘까?

The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.
A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.
https://reactjs.org/docs/render-props.html#gatsby-focus-wrapper

 

즉, react 에서 뭔가 작동하게 할 용도의 기능을 하나 완성 해 두고 나서, main.js 같은 곳에다가

import 카드체크 from 카드체크.js
...
<strictREACT?>
<카드체크 /> 
<strictREACT?/>

이런식으로 하던 것의 이야기다.

 

여기서 잠시 react 를 보자면...(아래는 component rendering 의 예시이다. Sara 를 주목.)

 

Components와 Props – React

A JavaScript library for building user interfaces

ko.reactjs.org

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

즉, 이때까지 알고 있던 것은 컴포넌트(component) 였다.

개념적으로 컴포넌트는 JavaScript 함수와 유사합니다. “props”라고 하는 임의의 입력을 받은 후, 화면에 어떻게 표시되는지를 기술하는 React 엘리먼트를 반환합니다.
// function component - simple way to build up component
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
// class component - ES6 way to build up component
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

오늘 마지막으로 글을 마치기 전에 전대미문의 코드를 하나만 더 해석하겠다.

 

function something({ $app, initialState }) {
	this.state = initialState
    this.$target = document.createElement("nav")
    this.$target.className = "something"
    $app.appendCHild(this.$target)
    
    ...

우선 this.$target 이다. 앞의 parameter 안의 $app 은 그렇다쳐도, 저 this 뒤의 $target 은 무엇이란 말인가?

매우 격하게 분노를 느꼈다. 그러던 중...정말 저 의문에 대한 답이 하나 있다.

 

Can someone explain the dollar sign in Javascript?

The code in question is here: var $item = $(this).parent().parent().find('input'); What is the purpose of the dollar sign in the variable name, why not just exclude it?

stackoverflow.com

해석:

1. 가장 많이 접했던 ${} (tempalte literal) 일 수도 있음.

2. 그냥 jQuery 에서 자주 쓰이는 일종의 표식.

보너스: 도대체 왜 달러사인을 쓰고 난리지?

Dollar Sign ($) Usage Summary

The dollar sign usage is semantics. It is an identifier name. Psychologically, it looks cute and convenient. Internally, it is just a function or an alpha-numeric variable reference. But it really makes no difference whether you use $ or _ or any other character as explained in the article on my website linked to from this page by the author of this page, for which I thank him.

The usage of the $, as pointed out by the Ecmascript specification, is a character that is allowed to be contained in a variable identifier name. Using the $ as the only character in an identifier name sure does make it look strange, but the difference is semantic in nature. As far as I know, doing so is no different than using any other character such as a, or b in an identifier name.

Again, Ecmascript specification documentation tells us that the $ should be used by internal code such as the jQuery framework simply out of convenience. So this means we should not use it in our code just because it looks cool, unless we are programming a framework that can really benefit from it, because it makes the global framework object unique and separate from the rest of the code.