'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:
- 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.scssto- SomePage.cshtml.css.
- Disable automatic bundling by the runtime, by adding to the cproj file: 
<DisableScopedCssBundling>true</DisableScopedCssBundling>
- 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
}
- Remove reference to - MyProject.styles.cssin- Layout.cshtml, and replace it with the new webpack bundle- razor.css.
- Add - *.cshtml.cssto- .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 | 
