vite-plugin-dashboard-metadata.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. const virtualModuleId = 'virtual:dashboard-extensions';
  6. const resolvedVirtualModuleId = `\0${virtualModuleId}`;
  7. /**
  8. * This Vite plugin scans the configured plugins for any dashboard extensions and dynamically
  9. * generates an import statement for each one, wrapped up in a `runDashboardExtensions()`
  10. * function which can then be imported and executed in the Dashboard app.
  11. */
  12. export function dashboardMetadataPlugin(options: { rootDir: string }): Plugin {
  13. let configLoaderApi: ConfigLoaderApi;
  14. let loadVendureConfigResult: LoadVendureConfigResult;
  15. return {
  16. name: 'vendure:dashboard-extensions-metadata',
  17. configResolved({ plugins }) {
  18. configLoaderApi = getConfigLoaderApi(plugins);
  19. },
  20. resolveId(id) {
  21. if (id === virtualModuleId) {
  22. return resolvedVirtualModuleId;
  23. }
  24. },
  25. async load(id) {
  26. if (id === resolvedVirtualModuleId) {
  27. if (!loadVendureConfigResult) {
  28. loadVendureConfigResult = await configLoaderApi.getVendureConfig();
  29. }
  30. const { pluginInfo } = loadVendureConfigResult;
  31. const pluginsWithExtensions =
  32. pluginInfo
  33. ?.map(
  34. ({ dashboardEntryPath, pluginPath }) =>
  35. dashboardEntryPath && path.join(pluginPath, dashboardEntryPath),
  36. )
  37. .filter(x => x != null) ?? [];
  38. this.info(`Found ${pluginsWithExtensions.length} Dashboard extensions`);
  39. return `
  40. export async function runDashboardExtensions() {
  41. ${pluginsWithExtensions
  42. .map(extension => {
  43. return `await import('${extension}');`;
  44. })
  45. .join('\n')}
  46. }`;
  47. }
  48. },
  49. };
  50. }
  51. /**
  52. * Converts an import path to a normalized path relative to the rootDir.
  53. */
  54. function normalizeImportPath(rootDir: string, importPath: string): string {
  55. const relativePath = path.relative(rootDir, importPath).replace(/\\/g, '/');
  56. return relativePath.replace(/\.tsx?$/, '.js');
  57. }