tailwind-reference.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import type { Plugin } from 'vite';
  2. const REFERENCE_LINE = '@reference "@vben/tailwind-config/theme";\n';
  3. /**
  4. * Auto-inject @reference into Vue SFC <style> blocks that use @apply.
  5. *
  6. * In Tailwind CSS v4, each Vue SFC <style scoped> block is processed as an
  7. * independent CSS module. If a style block uses @apply with custom theme
  8. * utilities (e.g. bg-primary, text-foreground), it needs access to the
  9. * @theme definition via @reference. This plugin auto-injects it so
  10. * individual components don't need to add it manually.
  11. */
  12. export function viteTailwindReferencePlugin(): Plugin {
  13. return {
  14. enforce: 'pre',
  15. name: 'vite:tailwind-reference',
  16. transform(code, id) {
  17. // Only process Vue SFC style blocks
  18. if (!id.includes('.vue')) {
  19. return null;
  20. }
  21. if (!id.includes('type=style')) {
  22. return null;
  23. }
  24. // Skip if already has @reference
  25. if (code.includes('@reference')) {
  26. return null;
  27. }
  28. // Only inject if the style block uses @apply
  29. if (!code.includes('@apply')) {
  30. return null;
  31. }
  32. return {
  33. code: REFERENCE_LINE + code,
  34. map: null,
  35. };
  36. },
  37. };
  38. }