Blazor UI Component Library


 I was reviewing some sample code the other day and I noticed that the index.html file had a lot of linked CSS files.  This got me thinking:

"Question: If UI components are in separate assemblies and use CSS isolation, would you still need to include the CSS file?"


The short answer is NO.  if you use CSS isolation, you don't need to include the CSS files.

We can go from this:

<link href="ComponentLibCSS.styles.css" rel="stylesheet" />

<link href="/_content/Assembly1/styles.css" rel="stylesheet" />

<link href="/_content/Assembly2/styles.css" rel="stylesheet" />

<link href="/_content/Assembly3/styles.css" rel="stylesheet" />

<link href="/_content/Assembly4/styles.css" rel="stylesheet" />

To just this:

<link href="ComponentLibCSS.styles.css" rel="stylesheet" />


A key point to remember for this you must be on .Net 5 or greater.  That is when CSS isolation was released.


Proof - Component Library

I am one to prove things to myself.  I have created a couple of projects to validate my thinking.

The first one is the basic Blazor web assembly project.  I have removed the counter page for simplicity.  Within this solution, I have a Razor component UI library that I add as a project dependency to the web assembly project.

The trick to building this was that the UI Component library must be a Razor Component Library project type.  Believe it or not, that was harder to figure out than I had expected it to be :-)



When the user clicks on the "Fetch Data" navigation link, there is a "loading spinner" that is a component in the component library.

The spinner is made up of HTML and CSS.  There is a 2-second delay in the fetching of the data, just to allow the user to see the spinner.

This worked very nicely.  I did not have to include any additional CSS files for the component library.





Proof - Nuget Package


The component library working, led me to ask the same question but for a NuGet package.

Again the short answer was Yes it would work.

To prove this, I cloned the web assembly project but not the component library.  I took the component library and built a local Nuget package.

With the NuGet package in hand, I added it to the cloned web assembly project and sure enough, everything ran as before.  I found this very impressive.

I have included all the source code I used to validate this.  This may have been obvious to most, but I wanted to prove it.  Besides you can never go wrong building Blazor Applications.




Comments

Popular posts from this blog

Yes, Blazor Server can scale!

Blazor new and improved Search Box

Blazor Wizard Step Component