SPFx CSS and Assets loaded from Azure Storage Account CDN

Tutorial on how to create Azure Storage Account CDN with hosted css files and load the css in SPFx (SharePoint Framework) React webpart .

Prerequisites


- Azure subscription

Create Storage Account


- Open the Azure Portal.
- Hit the Plus sign (New button) on the top left menu.
- Find Storage -> Storage account - blob, file, table, queue.
Velin Georgiev blog image

- Create Storage account be adding all the details.
- I have called mine velinstoragecdn and also created new resource group named velinstoragecdnARM to host it.
Velin Georgiev blog image
- Consider the Replication options, because the price vary depending on that. For the blog I have picked the cheapest "Locally-redundant storage (LRS)".

Create Blob Container


- Once the Azure storage account is created, access it and navigate to the Blob section in the blade.
Velin Georgiev blog image

- Click on the Containers and create new container to host the assets.
- I called mine spfx assets and it is from type Container.
Velin Georgiev blog image

- Upload one asset to the container so it can be tested later.
- Select the container -> Find the Upload option -> Upload CSS file.
Velin Georgiev blog image

Create Storage Account CDN


- Under the Storage Account Settings find -> Blob Service -> Azure CDN
Velin Georgiev blog image

- Create new endpoint
Velin Georgiev blog image

- Copy the url enpoint, the blob container name and the uploaded asset name so url can with this format be constructed:
https://<CDN_path>/<BLOB_Container_name>/<CSS_file_with_extension>

In my example the url looks like this
https://velincdn.azureedge.net/spfxassets/vendor.css

Load the CSS in SPFx webpart


- Add reference to the  SPComponentLoader  in the webpart ts file.
import { SPComponentLoader } from '@microsoft/sp-loader';

- Load the scripts in the constructor of the SPFx webpart:
export default class ReactWebPart extends BaseClientSideWebPart<IReactWebPartProps> {

  public constructor(context: IWebPartContext) {
    super();

    SPComponentLoader.loadCss("https://velincdn.azureedge.net/spfxassets/vendor.css");
  }
...

The css classes can now be used in the webpart.

Enable CORS for extra security


- Add origins for your tenant domains only for extra security.
- Find the Blob CORS options under -> Storage Account Settings -> Blob Service -> CORS
Velin Georgiev blog image

- Add your domain rules there
Velin Georgiev blog image

Comments