Access Static Resources

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.

Before you can import a static resource, create and upload the file.

To create and upload a static resource:

  1. From Setup, enter Static Resources in the Quick Find box, then select Static Resources.

  2. Click New.

  3. In the Name text box, enter the text that's used to identify the resource in your LWC code.

    A static resource name can contain only underscores and alphanumeric characters, and must be unique in your org. It must begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores.

  4. In the Description text area, specify an optional description of the resource.

  5. Click Browse to navigate to a local copy of the resource that you want to upload. The maximum file size is 5 MB. An org can have up to 250 MB of static resources.

  6. Set the Cache Control for user sessions, including API and Experience Cloud user sessions:

    • Private specifies that the static resource data cached on the Salesforce server must not be shared with other users. The static resource is stored in cache only for the current user’s session.
    • Public specifies that the static resource data cached on the Salesforce server is shared with other users in your organization for faster load times. After it’s cached, the resource is accessible to all Internet traffic, including unauthenticated users.
  7. Click Save.

For more information, see Salesforce Help: Static Resources.

Import a static resource using this syntax.

  • myResource—A name that refers to the static resource.
  • resourceReference—The name of the static resource.
  • namespace—If the static resource is in a managed package, this value is the namespace of the managed package.

Let’s look at some sample code.

The JavaScript code imports two resources: a Trailhead logo and an image of a Trailhead character.

A static resource can be an archive file with a nested directory structure. To reference an item in an archive, concatenate a string to create the path to the item, as the example does to build einsteinUrl.

To reference a resource in a template, use {property} syntax, which is the same syntax you use to reference any JavaScript property.

In a Salesforce DX project, static resources live in the /force-app/main/default/staticresources directory. You can’t create subdirectories of staticresources.

Create a .resource-meta metadata file for each resource. The metadata file defines the content type of the resource.

This code sample is the miscStaticResource component in the repo.

See Also