1
0

vite-plugin-tailwind-source.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { Plugin } from 'vite';
  2. import { CompileResult } from './utils/compiler.js';
  3. import { getDashboardPaths } from './utils/get-dashboard-paths.js';
  4. import { ConfigLoaderApi, getConfigLoaderApi } from './vite-plugin-config-loader.js';
  5. /**
  6. * This Vite plugin transforms the `app/styles.css` file to include a `@source` directive
  7. * for each dashboard extension's source directory. This allows Tailwind CSS to
  8. * include styles from these extensions when processing the CSS.
  9. */
  10. export function dashboardTailwindSourcePlugin(): Plugin {
  11. let configLoaderApi: ConfigLoaderApi;
  12. let loadVendureConfigResult: CompileResult;
  13. return {
  14. name: 'vendure:dashboard-tailwind-source',
  15. // Ensure this plugin runs before Tailwind CSS processing
  16. enforce: 'pre',
  17. configResolved({ plugins }) {
  18. configLoaderApi = getConfigLoaderApi(plugins);
  19. },
  20. async transform(src, id) {
  21. if (/app\/styles.css$/.test(id)) {
  22. if (!loadVendureConfigResult) {
  23. loadVendureConfigResult = await configLoaderApi.getVendureConfig();
  24. }
  25. const { pluginInfo } = loadVendureConfigResult;
  26. const dashboardExtensionDirs = getDashboardPaths(pluginInfo);
  27. const sources = dashboardExtensionDirs
  28. .map(extension => {
  29. return `@source '${extension}';`;
  30. })
  31. .join('\n');
  32. // Find the line with the specific comment and insert sources after it
  33. const lines = src.split('\n');
  34. const sourceCommentIndex = lines.findIndex(line =>
  35. line.includes(
  36. '/* @source rules from extensions will be added here by the dashboardTailwindSourcePlugin */',
  37. ),
  38. );
  39. if (sourceCommentIndex !== -1) {
  40. // Insert the sources after the comment line
  41. lines.splice(sourceCommentIndex + 1, 0, sources);
  42. const modifiedSrc = lines.join('\n');
  43. return {
  44. code: modifiedSrc,
  45. };
  46. }
  47. // If the comment is not found, append sources at the end
  48. return {
  49. code: src + '\n' + sources,
  50. };
  51. }
  52. },
  53. };
  54. }