Reference static files inside your component JavaScript code
Static files for your component are usually loaded globally and used across multiple components. This approach also means that the CSS and JavaScript are not loaded in inappropriate parts of the HTML document.
You may also want access to a specific image to render your component. There is a helper function to help simplify this task.
Before you start
Complete the steps in Configure static files in the manifest.json file
Steps
To reference static files inside your component:
-
Inside your
main.cjs
file, check that your function loads theinfo
object by includinginfo
afterinput
in the function signature.`module.exports = async function (input, info) {`
-
Within your function, use the following command to get the full URL of the static file you want to reference:
info.ctx.getStaticResourceUrl('Images/image.jpg')
-
Display an image within your component using this method inside an
<image>
element:let image = info.ctx.getStaticResourceUrl("Images/image.jpg"); return `<div class="test-static-files-component"> <img src="${image}" /> </div>`;
-
Run the local development server and preview your component.
If you have configured your manifest correctly and followed the steps in this how to guide, you will see your static image rendered in the component.