'ASP.NET Core CSS Isolation with Webpack

My ASP.NET Core RazorPages project uses Webpack. I also want to use CSS Isolation.

Every RazorPage Foo.cshtml has an associated css file Foo.cshtml.css. These undergo css isolation and bundling by the runtime, and placed in a subdirectory of obj/. The runtime appears to serve the final bundle from wwwroot/ProjectName.styles.css (but it isn't really there, it's an "implementation detail").

Bad option 1: use Webpack. I could rename these to Foo.cshtml.scss and make them available to Webpack. But I doubt it's possible (?) to compile them (in-place and unbundled) so the runtime can find them.

Bad option 2: use runtime. I could exclude these from Webpack altogether, and allow the runtime to manage them. But then I can't use scss, or minification.

How can I use the CSS Isolation feature and Webpack simultaneously?



Solution 1:[1]

I found a way:

  1. The css isolated file must be css - it cannot be scss. So install an IDE extension that compiles scss->css on save, alternatively, add this as a build step so it's available in CI. Configure it to compile in-place SomePage.cshtml.scss to SomePage.cshtml.css.

  2. Disable automatic bundling by the runtime, by adding to the cproj file:

<DisableScopedCssBundling>true</DisableScopedCssBundling>
  1. Configure webpack to output another bundle, specifically for the isolated css files:
entry: {

  site:  // normal site bundle

  razor: // css files in obj/(Debug|Release)/net6.0/scopedcss/**/*.css
         // can use glob.sync() above to find all css files automatically
}
  1. Remove reference to MyProject.styles.css in Layout.cshtml, and replace it with the new webpack bundle razor.css.

  2. Add *.cshtml.css to .gitignore

This is not ideal due to the need for the workaround in (1). However, it works perfectly.

If I find a better way then I'll update this. If you have a better answer, please add it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1