vite-plugin-tailwind-source.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import path from 'path';
  2. import { Plugin } from 'vite';
  3. import { LoadVendureConfigResult } from './utils/config-loader.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: LoadVendureConfigResult;
  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 =
  27. pluginInfo
  28. ?.map(
  29. ({ dashboardEntryPath, pluginPath }) =>
  30. dashboardEntryPath && path.join(pluginPath, path.dirname(dashboardEntryPath)),
  31. )
  32. .filter(x => x != null) ?? [];
  33. const sources = dashboardExtensionDirs
  34. .map(extension => {
  35. return `@source '${extension}';`;
  36. })
  37. .join('\n');
  38. // Find the line with the specific comment and insert sources after it
  39. const lines = src.split('\n');
  40. const sourceCommentIndex = lines.findIndex(line =>
  41. line.includes(
  42. '/* @source rules from extensions will be added here by the dashboardTailwindSourcePlugin */',
  43. ),
  44. );
  45. if (sourceCommentIndex !== -1) {
  46. // Insert the sources after the comment line
  47. lines.splice(sourceCommentIndex + 1, 0, sources);
  48. const modifiedSrc = lines.join('\n');
  49. return {
  50. code: modifiedSrc,
  51. };
  52. }
  53. // If the comment is not found, append sources at the end
  54. return {
  55. code: src + '\n' + sources,
  56. };
  57. }
  58. },
  59. };
  60. }