Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags more
Archives
Today
Total
관리 메뉴

파스타집

자주 쓰는 기능을 모듈화 하는 방법 본문

Salesforce/LWC

자주 쓰는 기능을 모듈화 하는 방법

Vongole 2022. 12. 9. 15:32

LWC의 모듈화 방법은 두 가지가 있으며 서로 장단점이 있다. 

 

  1. JS파일을 분리하여 Import해서 사용하는 방법
    • 장점
      • 필요한 기능만 import하여 메모리를 아낄 수 있음
      • 다중 import가 가능하기 때문에 모듈 정의가 비교적 쉬움
    • 단점:
      • this의 컨텍스트 전환이 발생함
      • import해야하는 기능이 많아지는 경우 import문이 장황해짐
      • import된 모듈은 Read-Only이므로 내부 멤버의 변경이 불가능함
  2. JS 클래스를 정의하여 상속받아 사용하는 방법
    • 장점
      • this의 컨텍스트를 그대로 사용할 수 있음
      • import문이 간결해짐
      • 내부 멤버의 변경이 자유로움
    • 단점
      • 정의된 모든 것들이 상속되므로 메모리가 낭비될 수 있음
      • 다중 상속이 불가능하기 때문에 클래스 정의가 까다로움

LWC의 플랫폼 이벤트인 ShowToastEvent를 활용하여 간단한 toast message를 띄워보겠다. 첫 번째 방법을 사용할 것이며 일반 함수와 화살표 함수의 실행 방식에 유의하여 확인해보자.

toastBase.html
<template>
    <lightning-button-group>
        <lightning-button variant="brand" label="Toast" onclick={callToast}></lightning-button>
        <lightning-button variant="destructive" label="Arrow Toast" onclick={callArrowToast}></lightning-button>
    </lightning-button-group>
</template>
toastBase.js
import {LightningElement} from 'lwc';
import {toast, arrowToast} from 'c/toastModule';

export default class ToastBase extends LightningElement {

    callToast() {
        toast.call(this, {
            variant: 'SUCCESS',
            title: 'Hello',
            message: 'World'
        });
    }

    callArrowToast() {
        arrowToast(this, {
            variant: 'ERROR',
            title: 'Hello',
            message: 'World'
        });
    }
}
toastModule.js
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export function toast({variant = 'info', title, mode = 'dismissable', message, messageData} = {}) {
    this.dispatchEvent(new ShowToastEvent({variant, title, mode, message, messageData}));
}

export const arrowToast = (_this, {variant = 'info', title, mode = 'dismissable', message, messageData} = {}) => {
    this.dispatchEvent(new ShowToastEvent({variant, title, mode, message, messageData}));
}

모듈에서의 this는 기본적으로 undefined이기 때문에 일반 함수 또는 화살표 함수 어떤 방식으로 구현을 하더라도 bind, call, apply 및 파라미터를 활용하여 this의 컨텍스트(여기선 ToastBase 클래스의 인스턴스임)를 반드시 넘겨줘야 한다.

 

똑같이 동작하는 코드를 두 번째 방법인 클래스 상속을 통해 구현해보자.

toastBase.html
<template>
    <lightning-button variant="brand" label="Toast" onclick={callToast}></lightning-button>
</template>
toastBase.js
import LightningElementWrapper from 'c/lightningElementWrapper';

export default class ToastBase extends LightningElementWrapper {

    callToast() {
        this.toast({
            variant: 'SUCCESS',
            title: 'Hello',
            message: 'World'
        });
    }
}
lightningElementWrapper.js
import {LightningElement} from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export default class LightningElementWrapper extends LightningElement {
     
    toast({variant = 'info', title, mode = 'dismissable', message, messageData} = {}) {
        this.dispatchEvent(new ShowToastEvent({variant, title, mode, message, messageData}));
    }
}

상속받은 모든 기능을 자식이 그대로 사용할 수 있으며 this의 컨텍스트를 그대로 사용할 수 있기 때문에 호출이 간단하다. 필요하다면 toast() 메소드를 오버라이드하여 사용할 수도 있다.

 

결론
  • 무조건 쓰이는 기능이라 판단되면(toast, alert, clone, spinner관련 메소드 등...) 클래스 상속을 활용하자. 매 번 import하기 귀찮으니까.
  • 무조건 쓰이는건 아닌데 이번 프로젝트에서만 쓰일 것 같은 공통 기능(프로젝트 관련 상수, Validation 메소드 등)들은 파일을 분리해서 모듈화하자.
  • 사실 계속해서 쓰일지 안쓰일지 판단하는게 가장 어렵다. 일단 정의하고 차차 보완해나가야 한다
Comments