How to access Static Resources in Lightning Web Components(lwc)

This post explains how to access static resources in Lightning Web Components.

To import static resources we use the @salesforce/resourceUrl scoped module.
Static Resources can be archives (such as .zip and .jar files), images, style sheets, JavaScript, and other files.

Syntax

import myResource from '@salesforce/resourceUrl/resourceReference';

myResource  —> it is a name that refers to the static resource.
resourceReference —-> The name of the static resource in your Org.

Note:
If you are accessing managed package resource use namespace__managedResourceReference
namespace —> The namespace of the static resource.
managedResourceReference —>The name of the static resource in a managed package.

Example

in this example, I am uploading two resources one is .zip file and another file is a .jpg file.
.zip file contains another folder images in that folder we have two images.

StaticResourceDemo.html

<template>
    <lightning-card title="Static Resource Example" icon-name="custom:custom19">
        <div class="slds-m-around_medium">
            <img src={Sfdcimage1}>
            <img src={Sfdcimage2}>
            <img src={winterstricker}>
        </div>
    </lightning-card>
</template>

StaticResourceDemo.js

import { LightningElement } from 'lwc';
import TrailHead_Image from '@salesforce/resourceUrl/trailheadphoto';
import SFDC_Images from '@salesforce/resourceUrl/SFDCImages';
export default class StaticResourcesDemo extends LightningElement {
    Sfdcimage1 = SFDC_Images + '/images/winterstcikers.png';
    Sfdcimage2 = SFDC_Images + '/images/trailhead.png';
    winterstricker = TrailHead_Image;
}

StaticResourceDemo.js-meta.xml

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

Result

Source : https://www.salesforcecodecrack.com/2019/01/how-to-access-static-resources-in.html

Leave a Comment