In LWC you often need to load images, style sheets, JavaScript, and other files that are stored in Static Resources. In order to load the static resource in LWC you first need to import the static resource into LWC js file.
You can import static resources from the @salesforce/resourceUrl scoped module. Static resources can be archives (such as .zip and .jar files), images, stylesheets, JavaScript, and other files.
The syntax for importing static resource in LWC is below:
import resourceAlias from “@salesforce/resourceUrl/resourceName“;
resourceAlias —A variable name that you choose in the JavaScript file to represent the static resource..
resourceName—The actual name of the static resource that is uploaded to Salesforce..
Once you’ve imported the static resource in your JavaScript file, you can assign it to a local variable and use it in your component’s HTML file.
For an example, If you have a image inside the static resource and you wanted to refer the image from the static resource in the LWC, We can do that in the below way.
// miscStaticResource.js
import { LightningElement } from "lwc";
import TRAILHEAD_LOGO from "@salesforce/resourceUrl/trailhead_logo";
import TRAILHEAD_CHARACTERS from "@salesforce/resourceUrl/trailhead_characters";
export default class MiscStaticResource extends LightningElement {
// Expose the static resource URL for use in the template
trailheadLogoUrl = TRAILHEAD_LOGO;
// Expose URL of assets included inside an archive file
einsteinUrl = TRAILHEAD_CHARACTERS + "/images/einstein.png";
}
<!-- miscStaticResource.html -->
<template>
<lightning-card title="MiscStaticResource" icon-name="custom:custom19">
<div class="slds-m-around_medium">
<img src={trailheadLogoUrl} />
<img src={einsteinUrl} />
</div>
</lightning-card>
</template>
I hope this article helps to understand how we can load and refer the static resource files in LWC.
nice content