본문 바로가기
  • search_ _ _ _
  • search_ _ _ _
  • search_ _ _ _
Salesforce

[LWC] 공통css , 공통 js , 공통 이미지 생성 및 연동

by 오늘의갈비찜 2024. 7. 3.
728x90

1. static resources

- 화면 왼쪽상단에 톱니바퀴 클릭 - setup

 

- Custom Code  - static resources 검색

 

- 오른쪽 화면 New 버튼을 클릭해 범용적으로 사용 가능한 이미지나 css, js 를 저장 할 수 있다.

** css, js는 처음 한번만 파일을 올리면 vscode로 받아서 수정및 반영 할 수 있다.


**vscode안에서 css (한쌍인 resources -meta.xml)를 생성하고 deploy를 하는 방법도 있지만, 여러사람이 동시에 작업하는 환경에서는 폴더를 덮는 위험한 상황이 발생할 수있으므로(salesforce는 소스 코드 버전을 관리가 되지 않아 형상관리가 되지 않는다.)  권장하지 않는다.

 

 

2. 파일올리기

 

- new 클릭

 

- 이름은 파일명과 동일하게

 

- 범용적으로 사용할수 있게 Public으로 선택

 

 

 

 

 

3. vscode로 호출

 

- vscode 에서

manifest - package.xml 창에서 우크릭

SFDX : Retrieve Source in Manifest from Org 선택

모든 작업물들을 호출

 

- staticresources에서 우클릭하고 선택하면

staticresources안에 폴더만 호출된다.

 

****staticresources안으로  파일명.css , 파일명.resource-meta.xml 생성

 

 

 

4. 공통.css 링크

Settings - Advanced - Edit Head Markup 클릭

 

 

 

 

static resource에 생선된 css면
<link rel="stylesheet" href="{ basePath }/sfsites/c/resource/reset?{ versionKey }" />

경로를 타서 들어가는 거면
<link rel="stylesheet" href="{ basePath }/sfsites/c/resource/경로/reset.css?{ versionKey }" />

 

 

 

 

5. 공통.js 링크

 

<script src="{ basePath }/sfsites/c/resource/ui?{ versionKey }"></script>

 

 

**css는 괜찮은데  왜인지 js는 버전 업그레이드가 반영되지 않는다.

..................js링크는 주석을 걸어 놓는다. (응 쓸모없어..)

 

 

각각의 컨포넌트.js 마다 호출을 해주는게 더 안전하다고 한다.

 

......어렵...

 

 

내용 작성..

 



import { LightningElement } from 'lwc';
import { loadScript } from "lightning/platformResourceLoader";
import resourceUI from "@salesforce/resourceUrl/ui"; //ui는 호출하고 하는 파일명 ui.js이다.

export default class MainVisual extends LightningElement {  //MainVisual는 컨포넌트명
    scriptLoaded = false;
    renderedCallback() {
        if (!this.scriptLoaded) {
            this.scriptLoaded = true; // 중복 로드 방지
            Promise.all([
                // loadStyle(this, srmCommonAssets + "/css/reset.css"),
                // loadStyle(this, srmCommonAssets + "/css/common.css"),

                //loadStyle(this, srmCommonAssets + "/css/inquiryStyle.css"),
                loadScript(this, resourceUI)
            ])
                .then(() => {
                    // 스크립트 로드 후 작업
                    // ui.init();
                })
                .catch((error) => {
                    console.error("Error loading scripts or styles:", error);
                }).finally(() => {
                //this.conLnbActive();
            });
        }
    }
}

 

 

 

 

*** js 에러가 발생

( 내용은 아래 링크로!! )

 

https://x-x-search.tistory.com/entry/JavaScript-Cannot-read-properties-of-null

 

[JavaScript] Cannot read properties of null

로컬에서 잘 되던 JavaScript가 lwc에서 에러가 났다...  에러 :  Cannot read properties of null (reading 'classList') 찾아보니 우선순위의 문제라고 한다.   *** 해결방법 const visualActive = document.querySelec

x-x-search.tistory.com

 

 

 

 

 

 

 

 

****** css 호출, 위와 동일하긴한뎁..

 

productSearchFilter.css를  static resources에 저장해서 호출할 경우,

 

staticresources 바로 안으로 호출되었다.

 

그럼 위와 동일하게 호출이 가능하다....

 

// css 호출경우

import { LightningElement } from 'lwc';
import { loadStyle } from "lightning/platformResourceLoader";
import productSearch from "@salesforce/resourceUrl/productSearchFilter"; //productSearchFilter.css

  renderedCallback() {
    if (!this.scriptLoaded) {
        this.scriptLoaded = true; // 중복 로드 방지
        Promise.all([
          loadStyle(this, productSearch),
        ])
            .then(() => {
              
            })
            .catch((error) => {
                console.error("Error loading scripts or styles:", error);
            }).finally(() => {
        });
    }
}

 

 

 

 

****** 여러 css, js, img를 압축해서 marketPlace라는 폴더명으로 올린다면

 

css의 경로는

 

C:\User\***\salesforce\new\force-app\main\default\staticresources\marketPlace\marketPlace\어쩌구.css 가 된다.

 

C:\User\***\salesforce\   여기까지는 저장경로

new\                               처음 lwc 만들때 만드는 이름

force-app\main\default\staticresources\  staticresources까지의 경로

marketPlace\                                           압축폴더명

marketPlace\                                           압출폴더 안에 폴더명

 

import { LightningElement } from 'lwc';
import { loadStyle } from "lightning/platformResourceLoader";
import resourceUI from "@salesforce/resourceUrl/marketPlace";

export default class ProductBySearchFilter extends LightningElement {

  renderedCallback() {
    if (!this.scriptLoaded) {
        this.scriptLoaded = true; // 중복 로드 방지
        Promise.all([
           loadStyle(this, resourceUI + "/marketPlace/productSearchFilter.css"),
        ])
            .then(() => {
              
            })
            .catch((error) => {
                console.error("Error loading scripts or styles:", error);
            }).finally(() => {
        });
    }
}

 

 

 

 

 

 

 

 

 

6. 공통 이미지 링크

 

html

<img src={imgUrl} alt="">

 

 

js

import { LightningElement, track, api } from "lwc";
import asset from '@salesforce/resourceUrl/marketPlace';

export default class ProductThumbList extends LightningElement {
    
    imgUrl = asset + '/marketPlace/image-removebg-preview.png';

}
728x90

'Salesforce' 카테고리의 다른 글

[LWC] onclick 이벤트  (0) 2024.07.10
[LWC] LWR 생성 및 편집 (site 고객채널)  (0) 2024.07.03
[LWC] 페이지 편집 (Edit Page)  (0) 2024.07.03
[LWC] 생성하기 및 반영하기  (0) 2024.07.03