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

Rate this post

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

One Thought to “How to access Static Resources in Lightning Web Components(lwc)”

  1. I know this if off topic but I’m looking into starting my own weblog and was wondering what all is needed to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web savvy so I’m not 100 positive. Any recommendations or advice would be greatly appreciated. Thanks

Leave a Comment