Search code examples
tailwind-cssvitepostcss

Integrating tailwind v4 alpha with vite postcss config


So I've managed to get Tailwind v4 alpha working for starters. It uses the postcss.config.js file:

export default {
  plugins: {
    '@tailwindcss/postcss': {},
  }
};

However I read that I should be able to do something like this in my vite.config.js (and delete the postcss.config.js file):

@@ -1,5 +1,6 @@
 import { defineConfig } from "vite";
 import { sveltekit } from "@sveltejs/kit/vite";
+import tailwind from "tailwindcss";
 
 // @ts-expect-error process is a nodejs global
 const host = process.env.TAURI_DEV_HOST;
@@ -29,4 +30,9 @@ export default defineConfig(async () => ({
       ignored: ["**/src-tauri/**"],
     },
   },
+  css: {
+    postcss: {
+      plugins: [tailwind],
+    },
+  },
 }));

Unfortunately the following error rears it's ugly head:

[plugin:vite:css] [postcss] It looks like you're trying to use tailwindcss directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install @tailwindcss/postcss and update your PostCSS configuration.

More unfortunately, my package.json already includes @tailwindcss/postcss as a dev dependency:

"devDependencies": {
    "@sveltejs/adapter-static": "^3.0.5",
    "@sveltejs/kit": "^2.7.0",
    "@sveltejs/vite-plugin-svelte": "^4.0.0",
    "@tailwindcss/postcss": "4.0.0-beta.4",
    "@tauri-apps/cli": "^2",
    "svelte": "^5.0.0",
    "svelte-check": "^4.0.0",
    "tailwindcss": "4.0.0-beta.4",
    "tslib": "^2.8.0",
    "typescript": "^5.5.0",
    "vite": "^5.4.10"
  }

Why does this error still appear?


Solution

  • As per the documentation for Vite integration:

    If you're using Vite or a Vite-powered framework like SvelteKit or Remix, install Tailwind along with our new dedicated Vite plugin:

    $ npm install tailwindcss@next @tailwindcss/vite@next
    

    Next, add our Vite plugin to your vite.config.ts file:

    import { defineConfig } from 'vite';
    import tailwindcss from '@tailwindcss/vite';
    
    export default defineConfig({
      plugins: [
        tailwindcss()
       ],
    });
    

    Finally, import Tailwind into your main CSS file:

    @import "tailwindcss";
    

    So, in relation to your project, you'd:

    • Uninstall @tailwindcss/postcss
    • Install @tailwindcss/vite@next
    • import @tailwindcss/vite in the vite config, adding it to the plugins array.
    • Add @import "tailwindcss" to some global CSS file that the app imports.