vite-plugin-config-loader.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. const onConfigLoaded: Array<() => void> = [];
  15. return {
  16. name: configLoaderName,
  17. async buildStart() {
  18. this.info(`Loading Vendure config...`);
  19. try {
  20. const result = await loadVendureConfig({
  21. tempDir: options.tempDir,
  22. vendureConfigPath: options.vendureConfigPath,
  23. vendureConfigExport: options.vendureConfigExport,
  24. });
  25. vendureConfig = result.vendureConfig;
  26. this.info(`Vendure config loaded (using export "${result.exportedSymbolName}")`);
  27. } catch (e: unknown) {
  28. if (e instanceof Error) {
  29. this.error(`Error loading Vendure config: ${e.message}`);
  30. }
  31. }
  32. onConfigLoaded.forEach(fn => fn());
  33. },
  34. api: {
  35. getVendureConfig(): Promise<VendureConfig> {
  36. if (vendureConfig) {
  37. return Promise.resolve(vendureConfig);
  38. } else {
  39. return new Promise<VendureConfig>(resolve => {
  40. onConfigLoaded.push(() => {
  41. resolve(vendureConfig);
  42. });
  43. });
  44. }
  45. },
  46. } satisfies ConfigLoaderApi,
  47. };
  48. }
  49. /**
  50. * Inter-plugin dependencies implemented following the pattern given here:
  51. * https://rollupjs.org/plugin-development/#direct-plugin-communication
  52. */
  53. export function getConfigLoaderApi(plugins: readonly Plugin[]): ConfigLoaderApi {
  54. const parentPlugin = plugins.find(plugin => plugin.name === configLoaderName);
  55. if (!parentPlugin) {
  56. throw new Error(`This plugin depends on the "${configLoaderName}" plugin.`);
  57. }
  58. return parentPlugin.api as ConfigLoaderApi;
  59. }