Search code examples
cssasp.net-coreblazormaui-blazorrazor-class-library

How to share (export) a global (non-scoped) css file from razor class library between Blazor server and MAUI hybrid projects


From what I understood and observed, every css scoped file (*.razor.css) is automatically bundled (rewritten when necessary to ensure isolation) and exported in a project bundle {ASSEMBLY NAME}.bundle.scp.css during the build, and also linked by to the scoped component.

But what about non-scoped css files (global), it seems to be excluded in the process.

Situation:

I have the following projects:

Blazor Server project (BLproj) ----> Razor Class Library (LibProj) <---- MAUI/Blazor hybrid (MAUIHproj)

I need to use and reference from my main projects (BLproj and MAUIHproj) a global css file which is located in wwwroot of the LibProj.

Doing a css import (@import _Content/{ASSEMBLY LIB NAME}}/css/... ) in my main projects won't work since the file isn't being exported to start with.

What is the approach to handle this situation ?

Related docs: CSS isolation


Solution

  • While scoped css file are automatically exported, bundled and linked during the build, global (non-scoped) css file needs on the other hand to be manually linked, if it is intended to be used by the project referencing the library.

    The css link needs to be added in the head of the root html document (Location of <head> and <body> content) of the main project.

    Example:

    In order for the project BLproj to use additionalStyles.css which a non-scoped css file defined in the folder wwwroot/css of the LibProj, it needs to be linked in _Host.cshtml:

    ...
    <head>
        ...
        <link href="_content/{ASSEMBLY LIB NAME}/css/additionalStyles.css" rel="stylesheet" />
       ...
    </head>
    ...
    

    Ps: for a MAUI-hybrid project the html root file is wwwroot/index.html

    Docs