Use Images Uploaded as Static Resources
Static resources are a method for packaging one or more images, stylesheets, or
JavaScript files for use within Lightning web components, and other Salesforce customization
features.
Referencing an image stored in a Static Resource is straightforward, and fully documented. We present only a simple example here. See Access Static Resources the Lightning Web Component Developer Guide for complete details.
The critical elements of an offline-ready implementation are:
- Access the URL of the resource by importing it using the @salesforce/resourceUrl module.
- Provide the image URL via a getter function.
- Use the getter function for the src attribute of an img tag in your HTML template.
Example
// imageFromStaticResource.js
import { LightningElement } from 'lwc';
import TRAILHEAD_LOGO from '@salesforce/resourceUrl/trailhead_logo';
export default class ImageFromStaticResource extends LightningElement {
get trailheadLogoUrl() {
return TRAILHEAD_LOGO;
}
}
With the image URL provided by the getter function in the preceding component JavaScript, referencing the image in the HTML template is just like referencing any image in HTML. Use it in the src attribute of an HTML img tag.
<!-- imageFromStaticResource.html -->
<template>
<lightning-card>
Display an image directly from a static resource: {trailheadLogoUrl}
</lightning-card>
<template if:true={trailheadLogoUrl}>
<img src={trailheadLogoUrl}/>
</template>
</template>