LWC에서 GSAP 사용하기 (기본기능만)

ahncheer·2023년 6월 7일
0

LWC & LWR

목록 보기
27/45

왜 되는지 모르겠지만 작동이 되길래 써둡니다.
정확하지 않습니다!! Sites에서만 가능합니다.

1. JS 다운로드 하기


공식 사이트에서 Zip 파일을 다운받습니다.


간단한 테스트용으로 gsap.min.js 파일만 꺼내 다른 폴더에 따로 빼둡니다. 이 때 static Resource에 등록할 수 있도록 이름을 gsap.js로 바꿔주었습니다.

2. Static Resource에 등록

gsap이라는 이름으로, cache Control을 'Public'으로 지정해서 저장합니다.

3. 코드 작성

-- lwc033gsap.html

<template>
    <p>GSAP</p>
    <div class="box">123123!!</div>
    <button onclick={goRightBtn}>오른쪽으로</button>
</template>

-- lwc033gsap.css

.box{
    display: block;
    width: 50px;
    height: 50px;
    border-radius: 20px;
    background-color: aqua;
}

-- lwc033gsap.js

import { LightningElement, track } from 'lwc';
import { loadStyle, loadScript } from 'lightning/platformResourceLoader';
import GSAP from '@salesforce/resourceUrl/gsap'; 

export default class Lwc033gsap extends LightningElement {
    @track rightTarget = 20;

    renderedCallback() {
        Promise.all([
            loadScript(this, GSAP)
        ]).then(async () => {
            this.goRightBtn();
            
        }).catch((error) => {
            console.log('errorMsg : ', error);
        });
    }
    goRightBtn(){
        this.rightTarget = this.rightTarget + 200;
        const boxContent = this.template.querySelector(".box");
        console.log(boxContent, this.rightTarget);
        gsap.set(boxContent, {x: this.rightTarget});
    }
}

-- lwc033gsap.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"  fqn="Lwc028GetRecordImage">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
      <target>lightning__AppPage</target>
      <target>lightning__RecordPage</target>
      <target>lightning__HomePage</target>
      <target>lightningCommunity__Page</target>
      <target>lightningCommunity__Default</target>
    </targets>
</LightningComponentBundle>

4. 빌더 설정 변경


만들어 둔 sites의 빌더 > 톱니바퀴 아이콘 (설정) > CSP 옵션 변경 후 Locker 해제

5. 컴포넌트 배치 후 확인


드래그 해서 컴포넌트를 배치하면 renderedCallback에서 오른쪽 이동을 한번 불러왔기 때문에 살짝 오른쪽으로 가있습니다.
Publish를 하지 않아도, 상단의 Preview 버튼을 눌러 컴포넌트를 쉽게 확인 할 수 있습니다.
버튼을 누르면 더욱 오른쪽으로 이동한 것을 알 수 있습니다.

+) 기타
이 부분도 타 js를 불러와서 사용하는 것이기 때문에 같은 컴포넌트임에도 불구하고 CSP를 설정하지 않은 페이지에서는 동작하지 않습니다. (스샷참고)

Swiper처럼 돔 구조를 이용해 사용할 수 있을거라 예상하지만, 시도하지는 않았습니다.
참고 링크 : https://velog.io/@ahncheer/LWR%EC%97%90%EC%84%9C-LWC%EB%A1%9C-Swiper-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

profile
개인 공부 기록용.

0개의 댓글