1
0

vite-plugin-config-loader.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { VendureConfig } from '@vendure/core';
  2. import { Plugin } from 'vite';
  3. import { ConfigLoaderOptions, loadVendureConfig } from './config-loader.js';
  4. export interface ConfigLoaderApi {
  5. getVendureConfig(): Promise<VendureConfig>;
  6. }
  7. export const configLoaderName = 'vendure:config-loader';
  8. /**
  9. * This Vite plugin loads the VendureConfig from the specified file path, and
  10. * makes it available to other plugins via the `ConfigLoaderApi`.
  11. */
  12. export function configLoaderPlugin(options: ConfigLoaderOptions): Plugin {
  13. let vendureConfig: VendureConfig;
  14. let onConfigLoaded = () => {
  15. /* */
  16. };
  17. return {
  18. name: configLoaderName,
  19. async buildStart() {
  20. this.info(`Loading Vendure config...`);
  21. try {
  22. const result = await loadVendureConfig({
  23. tempDir: options.tempDir,
  24. vendureConfigPath: options.vendureConfigPath,
  25. vendureConfigExport: options.vendureConfigExport,
  26. });
  27. vendureConfig = result.vendureConfig;
  28. this.info(`Vendure config loaded (using export "${result.exportedSymbolName}")`);
  29. } catch (e: unknown) {
  30. if (e instanceof Error) {
  31. this.error(`Error loading Vendure config: ${e.message}`);
  32. }
  33. }
  34. onConfigLoaded();
  35. },
  36. api: {
  37. getVendureConfig(): Promise<VendureConfig> {
  38. if (vendureConfig) {
  39. return Promise.resolve(vendureConfig);
  40. } else {
  41. return new Promise<VendureConfig>(resolve => {
  42. onConfigLoaded = () => {
  43. resolve(vendureConfig);
  44. };
  45. });
  46. }
  47. },
  48. } satisfies ConfigLoaderApi,
  49. };
  50. }
  51. /**
  52. * Inter-plugin dependencies implemented following the pattern given here:
  53. * https://rollupjs.org/plugin-development/#direct-plugin-communication
  54. */
  55. export function getConfigLoaderApi(plugins: readonly Plugin[]): ConfigLoaderApi {
  56. const parentPlugin = plugins.find(plugin => plugin.name === configLoaderName);
  57. if (!parentPlugin) {
  58. throw new Error(`This plugin depends on the "${configLoaderName}" plugin.`);
  59. }
  60. return parentPlugin.api as ConfigLoaderApi;
  61. }