Search code examples
c#npmblazorbundleminify

How to minify static assets for a Blazor app


Background

I've been playing with Blazor recently. I created a sample application using a VS template.

Then I wanted to add some styling to it. So I found an example template here, copied the static assets to wwwroot folder, then linked required files in _Host.cshtml and everything looks good.

Questions

I ended up with a lot of files in my wwwroot folder:

wwwwroot structure

Question 1

Is there a way to bundle and minify the content of wwwroot? I tried naively wiring everything via webpack and it even output something, but then I had no idea how to link the files in _Host.cshtml.

Question 2

I can see that the same template is available via npm here. I know it is possible to use npm inside Blazor, but would it be possible to fetch the package, then minify it e.g. using webpack and output it to wwwroot? If so, how can I link it together with Blazor app then?


Solution

  • According to the Microsoft Documentation, one good way to do this is via WebOptimizer.

    I would not recommend using the BuildBundlerMinifier tool described in the comments above. It's unmaintained, does not work with dotnet tool, and has a hard dependency on .NETCore 2.0 (which can be very disruptive to a workflow — I ended up screwing up my dotnet7 SDK install in attempts to get this working).

    OTOH, Weboptimizer handles both bundling and minification directly from within the app itself, i.e., app.UseWebOptimizer().