When working with CSS isolation in a Razor class library, incorporating @import
is achievable but it requires manual setup.
The approach involves allowing CSS isolation to generate a CSS bundle and then manually adding the necessary imports to the file.
To accomplish this, a MSBuild task and target can be utilized.
Begin by defining a task in the project file that appends the import statement to the CSS bundle...
<UsingTask TaskName="InjectCssImport" TaskFactory="RoslynCodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
<ParameterGroup>
<FilePath ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Code Type="Fragment" Language="cs">
<![CDATA[
var css = File.ReadAllText(FilePath);
var cssWithInjectedImport = "@import <any-css-file>;" + Environment.NewLine + css;
File.WriteAllText(FilePath, cssWithInjectedImport);
]]>
</Code>
</Task>
</UsingTask>
...then establish a target that triggers the task...
<Target Name="InjectImportIntoCssBundle" AfterTargets="BundleScopedCssFiles">
<InjectCssImport FilePath="$(_ScopedCssProjectOutputPath)" />
</Target>
This method has been successfully implemented alongside Blazor within an RCL environment. The outcome is quite satisfactory!