vite-plugin-transform-index.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { Plugin, ResolvedConfig } from 'vite';
  2. /**
  3. * @description
  4. * This Vite plugin handles the scenario where the `base` path is set in the Vite config.
  5. * The default Vite behavior is to prepend the `base` path to all `href` and `src` attributes in the HTML,
  6. * but this causes the Vendure Dashboard not to load its assets correctly.
  7. *
  8. * This plugin removes the `base` path from all `href` and `src` attributes in the HTML,
  9. * and adds a `<base>` tag to the `<head>` of the HTML document.
  10. */
  11. export function transformIndexHtmlPlugin(): Plugin {
  12. let config: ResolvedConfig;
  13. return {
  14. name: 'vendure:vite-config-transform-index-html',
  15. configResolved(resolvedConfig) {
  16. // store the resolved config
  17. config = resolvedConfig;
  18. },
  19. // Only apply this plugin during the build phase
  20. apply: 'build',
  21. transformIndexHtml(html, ctx) {
  22. // Don't transform Storybook HTML files
  23. if (
  24. ctx.filename &&
  25. (ctx.filename.includes('iframe.html') || ctx.filename.includes('storybook'))
  26. ) {
  27. return html;
  28. }
  29. if (config.base && config.base !== '/') {
  30. // Remove the base path from hrefs and srcs
  31. const basePath = config.base.replace(/\/$/, ''); // Remove trailing slash
  32. // Single regex to handle both href and src attributes with any quote type
  33. const attributeRegex = new RegExp(`(href|src)=(["'])${basePath}/?`, 'g');
  34. let transformedHtml = html.replace(attributeRegex, '$1=$2');
  35. // Add base tag to head
  36. const baseTag = ` <base href="${config.base}">\n`;
  37. transformedHtml = transformedHtml.replace(/<head>/, `<head>\n${baseTag}`);
  38. return transformedHtml;
  39. }
  40. return html;
  41. },
  42. };
  43. }