
Picture this: You’ve just created your first SharePoint Framework webpart, and you’re ready to slap your company logo on it, and send it out the door.
It’s easy – you just reference your image in relation to your webpart file, via a require statement (which will push it into your ‘dist’ folder of assets), and embed that in an html img tag like so:
<img src="${require<string>('../../assets/logo.jpg')}" alt="My Company" />
Update: Thanks to Chris Kent for the suggestion on specifying the string type in order for this to work in JSX as well (which also removes the use of quotes and the dollar sign)
However, when you view your webpart, there’s nothing there. What happened? The problem is that the image is referenced by filename only, as it has no idea where the assets are that you deployed with your package, and thus its pointing to the image as if it lived in the same location of the page you are currently viewing.
The fix – add the below to the top of your webpart file before you reference any images (if you put an img reference after this statement, it won’t contain the public path of your deployed assets)
require('set-webpack-public-path!');
Including this will instruct your solution to include the path to your deployed assets when referencing them, and thus, you’ll be able to see your image, whether you’re viewing it in your development environment or on O365.
I hope this quick tip helped!
Cheers,
Matt