Search code examples
blazorblazor-server-sideasp.net-blazor

Blazor: what is the best way to include main page scripts and styles?


In default Blazor project we get Pages/_Host.cshtml file that contains something like a HTML template for the application.

Recently I created my first Razor Component Library (RCL) and it works. Here's the scripts part for it:

<script src="_content/Woof.Blazor/js/woof.js"></script>
<script src="_content/Woof.Blazor/js/modal.js"></script>
<script src="_content/Woof.Blazor/js/input.js"></script>
<script src="_content/Woof.Blazor/js/datatable.js"></script>
<script src="_content/Woof.Blazor/js/autocomplete.js"></script>

The scripts are included manually in my app. Is there a way for the library to add those files to the application template automagically? BTW, it would be sweet if style sheets could be added automagically too.

EDIT: I just tried to create a _Scripts.cshtml file, but it didn't work. Visual Studio shown a lot of weird errors probably caused by missing package, but I don't know. Making the scripts part a partial view? It's not really a part of MVC. So probably I'm wrong.

What I want to achieve is to replace the whole scripts part above with one line, including all predefined and preconfigured scripts from my library.


Solution

  • There is nothing available out of the box to do what you’re attempting. The reason is that sometimes the order of script and CSS tags really matters.

    For example, if I override some classes from Bootstrap but include my CSS files tag before the one for bootstrap then it won’t work. If CSS and JS files were automatically there would be no way to control order leading to this issue.

    From you’re question you list several scripts present in your library. I would suggest the approach to take is to bundle and minify those scripts into a single file. Then you would only need to add one reference in any consuming application. This would also speed up the loading of the consuming application as well, it would only need to load a single script, not 5.

    There are multiple ways you can achieve this but I think the most common right now is webpack. A quick google will bring up 10s of blog post showing configuration for this, for example, https://ideas.byteridge.com/webpack-minifying-your-production-bundle/. This can all be automated as well into a build pipeline so it can be used with full CI/CD.