Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor component isolated css with tailwind/postcss

Is it possible to use tailwind and postcss syntax for blazor component isolated css?

I really like Tailwind as a CSS framework specifically its use of postcss and the @apply functionality where you can bundle tailwinds css components into an individual class.

e.g.

.some-button {
    @apply px-4 py-2 bg-blue-400 text-white
}

I've been considering using Svelte because it offers both CSS isolation and postcss @apply syntax. However now that Blazor supports isolated CSS I would really like to take it a small step further and be able to write postcss styles from within component CSS.

So... any idea if that's possible yet?

like image 525
CT14.IT Avatar asked Dec 16 '20 09:12

CT14.IT


1 Answers

Yes, it's possible! Tested with .NET 5.0

You have to create a new npm project in the projects root directory.

  1. Use npm init to create a new npm project.
  2. Add the dependencies of tailwind and postcss with npm i -D postcss-cli autoprefixer postcss tailwindcss
  3. Add a config for postcss
// postcss.config.js
module.exports = {
    plugins: {
        tailwindcss: {},
        autoprefixer: {}
    }
}
  1. Add the tailwind.config.js to the project using npx tailwindcss init. If needed, you can replace the purge property to remove unused css classes. But this was a bit buggy in my tests when I used a Razor library.
// tailwind.config.js
purge: {
    enabled: true,
    content: [
        './**/*.html',
        './**/*.razor',
        './**/*.razor.css'
    ],
},
  1. Add a post-css buildscript to your .csproj file. This will apply postcss rules to the stylesheets bundled by Blazor after each build.

For Blazor projects:

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="npx postcss $(ProjectDir)obj\$(ConfigurationName)\net5.0\scopedcss\bundle\$(ProjectName).styles.css -r" />
</Target>

For Blazor component libraries:

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="npx postcss $(ProjectDir)obj\$(ConfigurationName)\net5.0\scopedcss\projectbundle\$(ProjectName).bundle.scp.css -r" />
</Target>

I'm not sure why the path differs, I can't find any documentation to it. If someone knows more, feel free to reply.

If there's anything that doesn't make sense or could be done better, please let me know!

like image 101
Philipp Sonntag Avatar answered Sep 28 '22 02:09

Philipp Sonntag